Android Volley PUT request
Asked Answered
S

7

11

i'm new to Volley and Android in general. Below is code snippet (Android using Volley) which i'm trying to execute, however it's the server returns a 400. Using another REST Client works perfectly. It's a request to the server using PUT method.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    sendRequest();
}

private void sendRequest() {
    RequestQueue queue = Volley.newRequestQueue(this);

    final JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("password", "ttttt");
        jsonObject.put("username", "tester3");
        jsonObject.put("token", "blah");
    } catch (JSONException e) {
        // handle exception
    }


    JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject,
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response) {
                    // response
                    Log.d("Response", response.toString());
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("Error.Response", error.toString());
                }
            }
    ) {

        @Override
        public Map<String, String> getHeaders()
        {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            return headers;
        }

        @Override
        public byte[] getBody() {

            try {
                Log.i("json", jsonObject.toString());
                return jsonObject.toString().getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }
    };

    queue.add(putRequest);
}

When i execute this code i always get a 400 Bad request back and i can't figure out why. Using another client like Postman, it works as expected. Here is the postman request:

Raw Request:
{ "token": "blah", "password": "ttttt", "username": "tester3" }

Headers: Content-Type: application/json

I can't see anything wrong with the request i'm hoping someone can point out what i'm doing wrong?

Sporule answered 2/11, 2014 at 7:45 Comment(4)
Did you happen to find the solution ? I'm also kind of stuck at the same situation.Showily
Afraid i haven't, ran out of time and moved onto using retrofit.Sporule
Even I ran out of time. Checkout out retrofit but couldn't grasp in short time. But your question helped solve the problem. Adding headers.put("Accept", "application/json" in the header solved it. Thanks.Showily
Glad it benefitted you :)Sporule
P
7

Sometimes , adding header "Content-Type", "application/json" in getHeaders() will not work its better to also override getBodyContentType() and return the header here.

So along with ,

public Map<String, String> getHeaders()
    {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json"); 
        return headers;
    }

also add,

    @Override
    public String getBodyContentType() {
        return "application/json";
    }

This worked for me while using POST.

Poultice answered 26/6, 2016 at 10:55 Comment(0)
S
4

JsonObjectRequest adds Content-Type: application/json; charset=utf-8 by default. Your headers.put("Content-Type", "application/json"); adds another Content-Type and some applications don't work with multiple Content-Type definitions. You should try to remove headers.put("Content-Type", "application/json");.

Serranid answered 26/1, 2017 at 18:54 Comment(1)
It solved my problem. Sometimes you just forget such basic stuff.Jameljamerson
A
3

I was looking for Android Volley Put (JSON) with request body in Kotlin language but all answers in Java. Maybe someone looking for answers in Kotlin so I created Put with request body in Kotlin language:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // let's say we have token, apiLink, val1, val2, val3 as a String
    // created a function sendPutRequest()
    sendPutRequest(token, apiLink, val1, val2, val3)
}

private fun sendPutRequest(
    token: String,
    apiLink: String,
    val1: String,
    val2: String,
    val3: String
) {

    val queue = Volley.newRequestQueue(this)
    val jsonObject = JSONObject()

    try {
        jsonObject.put("token", token)
        jsonObject.put("val1", val1)
        jsonObject.put("val2", val2)
        jsonObject.put("val3", val3)
    } catch (e: JSONException) {
        // handle exception
        Log.i("json_error: ", "$e")
    }

     val putRequest: JsonObjectRequest =
        object : JsonObjectRequest(
            Method.PUT, apiLink, jsonObject,
            Response.Listener { response ->
                // response
                Log.i("response: ", "$response")
            },
            Response.ErrorListener { error ->
                // error
                Log.i("error: ", "$error")
            }
        ) {

            override fun getHeaders(): Map<String, String> {
                val headers: MutableMap<String, String> =
                    HashMap()
                headers["Content-Type"] = "application/json"
                headers["Accept"] = "application/json"
                return headers
            }

            override fun getBody(): ByteArray {
                    Log.i("json", jsonObject.toString())
                    return jsonObject.toString().toByteArray(charset("UTF-8"))
            }

        }
    queue.add(putRequest)
}

Archegonium answered 28/3, 2020 at 19:18 Comment(0)
L
1

Just try with a StringRequest, like this:

StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
        new Response.Listener<String>()
        {
@Override
public void onResponse(String response) {
        // response
        Log.d("Response", response.toString());
        }
        },
        new Response.ErrorListener()
        {
@Override
public void onErrorResponse(VolleyError error) {
        // error
        Log.d("Error.Response", error.toString());
        }
        }
        ) {

@Override
public Map<String, String> getHeaders()
        {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        //or try with this:
        //headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        return headers;
        }
@Override
protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("password", "ttttt");
        params.put("username", "tester3");
        params.put("token", "blah");
        return params;
        }
        };

        queue.add(putRequest);
        }
Lepidus answered 26/12, 2016 at 14:4 Comment(0)
A
1
 @Override
public String getBodyContentType() {
    return "application/json";
}

This worked for me using a PUT request.

Acidophil answered 19/4, 2017 at 0:50 Comment(0)
S
-1

Some hosting service provider block certain request methods, such as PUT or DELETE - e.g. 000webhost blocks PUT and DELETE requests for free users. If PUT method is blocked on the host for some reason, you can substitute it with POST method. I know, this is not the best solution, but it works.

Saarinen answered 7/10, 2018 at 8:36 Comment(0)
M
-6

I spent a lot of time looking for how to do this. What worked for me was changing

Request.Method.PUT

to

Request.Method.POST
Monandry answered 19/5, 2015 at 3:3 Comment(2)
but this is question is about PUTTartuffe
You are a geniousConfection

© 2022 - 2024 — McMap. All rights reserved.