Search code examples
javaandroid-studiohttp-postandroid-volley

POST request with Volley with headers and body (java, android studio)


I am trying to send a POST request with Volley in Android Studio. However, I would like to set some headers and a body. How can I do this? In this case, the headers are id and key. Where should I add the body? I have tried to follow the numerous questions about these that are written in StackOverflow. However, it still seems like the headers and the body is not properly sent.

        try {
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String URL = "https://url.of.the.server";
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("Content-Type", "application/json");
            jsonBody.put("id", "oneapp.app.com");
            jsonBody.put("key", "fgs7902nskagdjs");
            final String requestBody = jsonBody.toString();

            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("VOLLEY", error.toString());
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                        return requestBody == null ? null : requestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                        return null;
                    }
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String>  params = new HashMap<String, String>();
                    params.put("Content-Type", "application/json");
                    params.put("id", "oneapp.app.com");
                    params.put("key", "fgs7902nskagdjs");

                    return params;
                }

                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }
            };
            Log.d("string", stringRequest.toString());
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }

Thank you very much for your help.


Solution

  • You are correctly setting the headers, you could try this

     try {
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String URL = "https://url.of.the.server";
    
            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("VOLLEY", error.toString());
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }
    
                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                         // request body goes here
                         JSONObject jsonBody = new JSONObject();
                         jsonBody.put("attribute1", "value1");
                         String requestBody = jsonBody.toString();
                        return requestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                        return null;
                    }
                }
    
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String>  params = new HashMap<String, String>();
                    params.put("Content-Type", "application/json");
                    params.put("id", "oneapp.app.com");
                    params.put("key", "fgs7902nskagdjs");
    
                    return params;
                }
    
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }
            };
            Log.d("string", stringRequest.toString());
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    For example, if request body is

    {
      name: "name1",
      email: "email1"
    }
    

    getBody method would be

    @Override
    public byte[] getBody() throws AuthFailureError {
     JSONObject jsonBody = new JSONObject();
     jsonBody.put("name", "name1");
     jsonBody.put("email", "email1");
     String requestBody = jsonBody.toString();
     return requestBody.getBytes("utf-8");
    }