实际上,当我们调用API并以JSON格式发送请求时,我们期望响应也会变成JSON格式 . 但是这里后端团队以String格式向我发送响应,因此我的onErrorResponse()方法被调用 . 这里我的状态代码是200.但是由于响应的格式没有在onResponse()方法上执行 . 那么请你帮我解决这个问题吗?我可能必须在这里使用CustomRequest . 任何建议将不胜感激 . 谢谢
我使用了volley json对象请求来访问服务器 .
My Request format is:
JSONObject json1 = new JSONObject();
try{
json1.put("","");
}catch(JSONException e){
e.printStackTrace();
}
new SampleJsonObjTask(MainActivity.this, json1);
而我的 SampleJsonObjTask 课程是:
public class SampleJsonObjTask {
public static ProgressDialog progress;
private static RequestQueue queue;
JSONObject main;
JsonObjectRequest req;
private MainActivity context;
public SampleJsonObjTask(MainActivity context, JSONObject main) {
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
this.context = context;
this.main = main;
ResponseTask();
}
private void ResponseTask() {
if (queue == null) {
queue = Volley.newRequestQueue(context);
}
req = new JsonObjectRequest(Request.Method.POST, "", main,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
progress.dismiss();
Log.e("response","response--->"+response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "error--->" + error.toString());
NetworkResponse response = error.networkResponse;
Log.e("statusCode","statusCode--->"+response.statusCode);
String json = null;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
break;
case 401:
json = new String(response.data);
break;
case 502:
json = new String(response.data);
break;
case 200:
json = new String(response.data);
break;
}
progress.dismiss();
}
}
})
{
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1f));
queue.add(req);
}}
这里 Response coming like string format that is Value OK, please help me to how to get the string response which i have mentioned below.
com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject
如何使用json对象请求获取此字符串响应 .
1 回答