How to get the JSONObject server response in Volley

拈花ヽ惹草 提交于 2019-12-20 04:54:44

问题


protected JSONObject executeGet(String URL) throws CloudAppException {
    JSONObject response = new JSONObject();
    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject serverResponse) {
                    try {
                        response = serverResponse;
                        VolleyLog.v("Response:%n %s", serverResponse.toString(4));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    });

    RequestHandler.addToRequestQueue(req);

    return response;
}

Ideally, I want to parse the response on my own, but I'm blanking on as to how to get the executeGet method to return the server response.


回答1:


You need to extend the request class and in your custom request class override the parseNetworkResponse method and do your own parsing.

Here is a sample :

public class CustomRequest extends Request {
    // the response listener
    private Response.Listener listener;

    public CustomRequest(int requestMethod, String url, Response.Listener responseListener, Response.ErrorListener errorListener) { 
        super(requestMethod, url, errorListener); // Call parent constructor
        this.listener = responseListener;
    }

    // Same as JsonObjectRequest#parseNetworkResponse
    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    public int compareTo(Request other) {
        return 0;
    }

    @Override
    protected void deliverResponse(Object response) {
        if (listener!=null)
            listener.onResponse(response);      
    }        
}


来源:https://stackoverflow.com/questions/21210045/how-to-get-the-jsonobject-server-response-in-volley

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!