【问题标题】:How to handle string response from php using android volley JsonObjectRequest [com.android.volley.ParseError: org.json.JSONException]?如何使用 android volley JsonObjectRequest [com.android.volley.ParseError: org.json.JSONException] 处理来自 php 的字符串响应?
【发布时间】:2018-10-23 23:19:24
【问题描述】:

实际上,当我们调用 API 并以 JSON 格式发送请求时,我们期望响应也变成 JSON 格式。但是这里后端团队以字符串格式向我发送响应,因此我的 onErrorResponse () 方法被调用。这里我的状态码是 200。但是由于响应的格式没有执行 onResponse() 方法。所以你能帮我处理这个吗?可能我必须在这里使用 CustomRequest 。任何建议将不胜感激。谢谢

我已经使用 volley json 对象请求来访问服务器。

我的请求格式是:

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);

    }}

这里的响应类似于字符串格式,值OK,请帮助我如何获取我在下面提到的字符串响应。

com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject

如何通过json对象请求得到这个字符串响应。

【问题讨论】:

    标签: json android-volley android-json jsonexception


    【解决方案1】:
    RequestQueue queue = Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            dialog.cancel();
                            Log.d("response", response);
                        }catch (Exception e){
                            volleyResponseCallBack.onFailure("Something went wrong!");
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        String message = null;
                        dialog.cancel();
    
                        if (volleyError instanceof NetworkError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                        } else if (volleyError instanceof ServerError) {
                            message = "The server could not be found. Please try again after some time!!";
                        } else if (volleyError instanceof AuthFailureError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                        } else if (volleyError instanceof ParseError) {
                            message = "Parsing error! Please try again after some time!!";
                        } else if (volleyError instanceof NoConnectionError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                        } else if (volleyError instanceof TimeoutError) {
                            message = "Connection TimeOut! Please check your internet connection.";
                        }
    
                        if (!(message == null)) {
                            Log.d("response", message);
                        }
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/json");
                return params;
            }
        };
    
    
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    

    【讨论】:

    • 是否有任何可能通过使用 JsonObjectRequest 来处理的响应是我在下面给出的。不使用 stringRequest ? com.android.volley.ParseError: org.json.JSONException: 类型 java.lang.String 的值 OK 无法转换为 JSONObject
    • 记录来自服务器的响应,你从服务器得到什么,因为它是 JSON 解析异常,。首先打印响应你得到什么?
    • 是的,我已经打印了日志,响应是 org.json.JSONException:Java.lang.String 类型的值 OK 无法转换为 JSONObject
    • 实际上当我们调用 API 并以 JSON 格式发送请求时,我们期望响应也变成 JSON 格式。但是这里后端团队以字符串格式向我发送响应,因此我的 onErrorResponse () 方法被调用。这里我的状态码是 200。但是由于响应的格式没有执行 onResponse() 方法。所以你能帮我处理这个吗?可能我必须在这里使用 CustomRequest 。任何建议都会受到赞赏。谢谢
    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多