Android Volley POST request with header and body

Viewed 10794

My code is trying to POST data to a server and I need to add a header, I am using the Volley library.

The request works if I do not include the "getparams" method, I am able to post but with no data.

If I include the "getparams" method, the request fails with a 400 (Bad request).

I have not been able to find out where the error is.

         public void tryPost() {
    RequestQueue queue = Volley.newRequestQueue(this);

    String serverUrl = "http://10.0.2.2:3000/tasks";



    StringRequest stringRequest = new StringRequest(Request.Method.POST, serverUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("TAG", "response = "+ response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("TAG", "Error = "+ error);
        }
    })
    {
        //
        @Override
        public Map<String, String> getHeaders()  {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json");
            return headers;
        }
        ////
        @Override
        public Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("userId","sargent"); 
            params.put("password","1234567"); 
            return params; //return the parameters
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
    }
4 Answers

please check this link:

StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String s) {
        ///handle response from service
    }, new ErrorResponse() {
      @Override
      public void onErrorResponse(VolleyError volleyError) {
        //handle error response
      }
  }) {
      @Override
      protected Map<String, String> getParams() throws AuthFailureError {
          Map<String, String> params = new HashMap<String, String>();
          //add params <key,value>
          return params;
      }

      @Override
      public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> headers = Constants.getHeaders(context);
        // add headers <key,value>
        String credentials = USERNAME+":"+PASSWORD;
        String auth = "Basic "
                + Base64.encodeToString(credentials.getBytes(),
                Base64.NO_WRAP);
        headers.put("Authorization", auth);
        return headers;
      }
  };
 mQueue.add(request);

https://gist.github.com/jchernandez/5bec1913af80e2923da8

For POST Requests, for the Header part you have to override the getHeaders() 'function', and for ** payload/body** of the request you can either provide a JsonObject as a parameter to your 'request' or you can override getParams() 'function'

Posting Code For Kotlin Programmers:

// Creating Json Payload

val requestJsonPayloadMap = mutableMapOf<String, String>()
        requestJsonPayloadMap["param1"] = "param1Value"
        requestJsonPayloadMap["param2"] = "param2Value"

        // Creating JSON Object out of the Hash-map
        val requestJSONObject = JSONObject(requestJsonPayloadMap)

// Passing the above payload to the request below [then no need to override the 'getParams()' method]

val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, requestJSONObject,
            Response.Listener {
                // Success Part  
            },

            Response.ErrorListener {
                // Failure Part
            }
        ) {
            // Providing Request Headers

            override fun getHeaders(): Map<String, String> {
               // Create HashMap of your Headers as the example provided below

                val headers = HashMap<String, String>()
                headers["Content-Type"] = "application/json"
                headers["app_id"] = APP_ID
                headers["app_key"] = API_KEY

                return headers
            }

            // Either override the below method or pass the payload as parameter above, dont do both 

            override fun getParams(): Map<String, String> {
               // Create HashMap of your params as the example provided below

                val headers = HashMap<String, String>()
                headers["param1"] = "param1Value"
                headers["param2"] = "param2Value"
                headers["param3"] = "param3Value"

                return headers
            }
        }
Related