Volley之自定义Request(三)

Volley框架自带的有图片请求(ImageRequest),字符串请求(StringRequest),Json请求(JsonObjectRequest).我们开篇介绍Volley的时候,已经说过Volley的代码和设计短小精悍,易于定制.
下面我们以一个例子讲解自定义请求Request.为了演示方便,我们自定义一个关于Json请求的Request

1,首先我们继承Request类
然后实现parseNetworkResponse(NetworkResponse response)和deliverResponse(JSONObject response)方法.

parseNetworkResponse(NetworkResponse response)用于将获取到的网络结果转换为需要的对象,例如JsonObject,Bitmap等.

deliverResponse(JSONObject response)主要用于将得到的结果回调到主线程

/**
 * Created by zhaolei on 2017/2/15.
 */

public class MyJsonRequest extends Request {

    private Response.Listener mResponseListener ;
    private static final String TAG = "request";
    public MyJsonRequest(int method, String url,Response.Listener responseListenr, Response.ErrorListener listener) {
        super(method, url, listener);
        this.mResponseListener = responseListenr;
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            Log.i(TAG,new String(response.data,"utf-8"));
            Log.i(TAG,response.headers.toString());

            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            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
    protected void deliverResponse(JSONObject response) {
        if(mResponseListener != null){
            mResponseListener.onResponse(response);
        }
    }
}

2,还是以请求天气为例,获取北京天气数据

private void getWeatherData() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        MyJsonRequest request = new MyJsonRequest(Request.Method.GET,
                                                  "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8",
                                                  new Response.Listener() {

            @Override
            public void onResponse(JSONObject response) {
                Log.i(TAG, "onResponse: " + response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: "+error.toString());
            }
        });

        requestQueue.add(request);
    }

至此,自定义请求Request完毕,有没有感觉Volley的设计很cool?

你可能感兴趣的:(Volley之自定义Request(三))