Not able to POST JSONObject in the body using Volley StringRequest
Asked Answered
E

1

0

I'm trying to POST a JSONObject in the body of a volley StringRequest but unfortunately the server receives an empty body. The logs print the correct mRequestBody string as soon as the JSONObject is created and also in getBody()(see comments in the code). When I paste the printed mRequestBody in the Postman, it works perfectly. May I know what I'm doing wrong here and why it works from postman and not the app.

Postman

enter image description here

Code:

private void makeJSONObjectSend() {


    try {
        JSONObject jsonBody = new JSONObject();

        jsonBody.put("FROMDATE", getFromSP("selectedFTimeValue"));
        jsonBody.put("TODATE", getToTime());
        if (jArraySelectedNo != null && jArraySelectedNo.length() > 0) {
            jsonBody.put("EMPNUMBER", jArraySelectedNo);
        } else {
            jsonBody.put("EMPNUMBER", new JSONArray());
        }
        if (jArraySelectedCounty != null && jArraySelectedCounty.length() > 0) {
            jsonBody.put("COUNTRYNAME", jArraySelectedCounty);
        } else {
            jsonBody.put("COUNTRYNAME", new JSONArray());
        }
        if (jArraySelectedState != null && jArraySelectedState.length() > 0) {
            jsonBody.put("STATENAME", jArraySelectedState);
        } else {
            jsonBody.put("STATENAME", new JSONArray());
        }

        String mRequestBody = jsonBody.toString().replace("\\/", "/");

        Log.i("LOG_VOLLEY",mRequestBody); 
        //Here 'LOG_VOLLEY' prints correct JSONObject which works in postman
        //I/LOG_VOLLEY:  {"FROMDATE":"23/10/2021 13:52:00","TODATE":"24/10/2021 13:52:11","EMPNUMBER":["96940"],"COUNTRYNAME":["US"],"STATENAME":["AK"]}

        String URL = "http://myTestapi.com:xxx/folder/xxxx/GetPartEmpInfo";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG_VOLLEY-22", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG_VOLLEY", error.toString());
                NetworkResponse response = error.networkResponse;
                if (error instanceof ServerError && response != null) {
                    try {
                        String res = new String(response.data,
                                HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                        Log.e("LOG_VOLLEY", res);
                        
                    } catch (UnsupportedEncodingException | JSONException e1) {
                        e1.printStackTrace();
                    } // returned data is not JSONObject?
                }
            }
        }) { 

            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                Log.i("LOG_VOLLEY2", mRequestBody);
                //Here 'LOG_VOLLEY2' prints correct JSONObject which works in postman
                //I/LOG_VOLLEY2:  {"FROMDATE":"23/10/2021 13:52:00","TODATE":"24/10/2021 13:52:11","EMPNUMBER":["96940"],"COUNTRYNAME":["US"],"STATENAME":["AK"]}
                return mRequestBody == null ? null : mRequestBody.getBytes(StandardCharsets.UTF_8);
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {

                if (response != null) {
                    String responseString = "";
                    responseString = String.valueOf(response.data);
                    Log.i("LOG_VOLLEY-2", responseString);
                }
                //return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                return super.parseNetworkResponse(response);
            }

            //This is for Headers
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                params.put("Authorization", "Bearer " + getFromSP("token"));
                return params;
            }

        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                240000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        VolleyLog.DEBUG = true;

        if (requestQueue2 == null) {
            requestQueue2 = Volley.newRequestQueue(this);
            requestQueue2.add(stringRequest);
        } else {
            requestQueue2.add(stringRequest);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
Escent answered 18/11, 2021 at 4:3 Comment(0)
E
1

I finally made it work. I was using this line in params.put("Content-Type", "application/x-www-form-urlencoded") in the getHeaders() .

Changing that to params.put("Content-Type", "application/json"); made it fix the issue.

Escent answered 18/11, 2021 at 5:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.