How to get the JSONObject server response in Volley

前端 未结 1 987
栀梦
栀梦 2021-01-24 03:34
protected JSONObject executeGet(String URL) throws CloudAppException {
    JSONObject response = new JSONObject();
    JsonObjectRequest req = new JsonObjectRequest(Requ         


        
相关标签:
1条回答
  • 2021-01-24 04:09

    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);      
        }        
    }
    
    0 讨论(0)
提交回复
热议问题