在使用getHeader和getParams时,排除Post JsonObjectRequest忽略参数

我试图连接API url =“api地址”它接受两个头types应用程序/ json在json和应用程序/ xml重新响应在xml中响应。 我需要打JSON与JSON参数和响应也将以JSON格式。 使用android volley Post请求与JsonObjectRequest使用getHeaders设置标题它连接到服务器,但getParams设置参数不起作用。

RequestQueue queue = Volley.newRequestQueue(this); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Constants.BASE_URL + Constants.LOGIN, null, response, response_error) { /** * Passing some request headers * */ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); return headers; } @Override protected Map<String, String> getPostParams() throws AuthFailureError { // TODO Auto-generated method stub Map<String, String> params = new HashMap<String, String>(); params.put("key", "value"); return params; } }; // implementation of listeners Response.Listener<JSONObject> response = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); Log.e("responce", response.toString()); // msgResponse.setText(response.toString()); hideProgressDialog(); } }; Response.ErrorListener response_error = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("error responce", error.getMessage()); VolleyLog.d(TAG, "Error: " + error.getMessage()); hideProgressDialog(); } }; //get params never get called //i also tried alternative to send params but does not works. Map<String, String> params = new HashMap<String, String>(); params.put("key", "value"); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Constants.BASE_URL + Constants.LOGIN, new JSONObject(params), response, response_error) { /** * Passing some request headers * */ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); return headers; } }; any type of help will be appretiated, Thanks in advance. 

Solutions Collecting From Web of "在使用getHeader和getParams时,排除Post JsonObjectRequest忽略参数"

Volley会忽略你的Content-Type设置,如果你想修改content-type,你可以重写getBodyContentType方法:

 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, new JSONObject(params), response, response_error) { @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } } 

为什么凌空忽略你的参数? 看看我的另一个答案 。

Volley JsonObjectRequest发布请求不起作用

从这个post的其他答案开始:您可以创build一个自定义的JSONObjectReuqest