无法使用 Volley StringRequest 在主体中 POST JSONObject

Not able to POST JSONObject in the body using Volley StringRequest

我正在尝试 POST 一个 JSONObject 到 volley StringRequest 的正文中,但不幸的是服务器收到一个空的正文。一旦创建了 JSONObject,日志就会打印正确的 mRequestBody 字符串,并且还会在 getBody() 中打印(请参阅代码中的注释)。当我将打印的 mRequestBody 粘贴到 Postman 中时,它工作得很好。我可以知道我在这里做错了什么以及为什么它适用于邮递员而不是应用程序。

邮递员

代码:

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();
    }

}

我终于成功了。我在 getHeaders() 中的 params.put("Content-Type", "application/x-www-form-urlencoded") 中使用了这一行。

将其更改为 params.put("Content-Type", "application/json"); 即可解决问题。