我想使用POST方法将JSONObject发送到服务器。我已经使用了volley库来传递字符串参数,它可以正常工作,但是如果我尝试使用json对象,则会显示调用json对象的错误。这是我的代码。
private void makeJsonObjReq() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* 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; charset=utf-8");
return headers;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("un", "xyz@gmail.com");
params.put("p", "somepasswordhere");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,tag_json_obj);
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
我的服务器错误信息为:
[10031] BasicNetwork.performRequest: 返回码 401,响应不符合预期
如何解决这个问题。我想在头部添加application/json;charset=utf-8
,请检查我的代码是否正确。请给我一些建议来克服这个问题。
JsonObjectRequest
中的第三个参数用于以JsonObject
形式传递POST参数。而对于头部,您需要发送两个单独的值,一个用于Content-Type,另一个用于Charset。 - Pr38y