【发布时间】:2018-02-08 23:06:10
【问题描述】:
我正在使用 volley 库访问 Web 服务。在这个库中,我需要附加标头来发布请求,但是在访问 Web 服务时出现错误,即“onErrorResponse:null”
// 代码
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("response", response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
Toast.makeText(getActivity(), R.string.txt_error_occured, Toast.LENGTH_LONG).show();
pDialog.hide();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("policyNo", policyNo);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Content-Type", "application/json; charset=utf-8");
params.put("User-agent", "My useragent");
return params;
}
};
// 将请求添加到请求队列 AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
【问题讨论】:
-
你怎么知道错误是因为标题?
-
试试这种方式:使用
StringRequest代替JsonObjectRequest并且不要在参数中添加Content-Type,只传递需要值的参数。有时响应以json字符串形式出现,新手认为必须使用JSON但它应该需要正常的StringRequest。
标签: android json error-handling http-headers android-volley