【问题标题】:Not able to POST JSONObject in the body using Volley StringRequest无法使用 Volley StringRequest 在正文中发布 JSONObject
【发布时间】:2021-12-29 00:32:30
【问题描述】:

我正在尝试在凌空 StringRequest 的正文中发布 JSONObject,但不幸的是服务器收到了一个空正文。一旦创建了 JSONObject,日志就会打印出正确的 mRequestBody 字符串,并且还会在 getBody() 中打印(参见代码中的 cmets)。当我将打印的mRequestBody 粘贴到邮递员中时,它可以完美运行。我可以知道我在这里做错了什么以及为什么它在邮递员而不是应用程序中有效。

邮递员

代码:

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

}

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多