在POST方法的Volley Stringrequest中将application / json设置为标头

时间:2016-12-28 10:38:06

标签: android json android-volley

我想将application / json设置为Content类型,但是甚至在将getBodyContentType()覆盖到application / json后得到Volley服务器错误。

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        listener.onResponse(response);
                        Log.d("Response",response.toString());

                    } catch (Exception e) {
                        e.printStackTrace();
                        if (response.length() == 0) {
                            Log.d("ERROR : ", "NO RESPONSE");
                        } else {
                            Log.d("ERROR : ", "EXCEPTION");
                        }
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    listener.onError(error.toString());
                    Log.d("Error.Response", error.toString());
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
                params.put("macId", macValue);
            return params;
        }
      @Override
        public String getBodyContentType() {
            return "application/json";
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(postRequest);
}

注意:请在代码段中提供答案

2 个答案:

答案 0 :(得分:0)

覆盖以下方法:

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

并覆盖getHeaders并且不传递任何内容:

   @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        return headers;
    }

它会起作用。

答案 1 :(得分:0)

首先检查邮递员的网络服务......