Android网络通信必备神器Volley详解——实现一个自定义的Request(以Gson为例)

虽然Volley已经提供了对于String,图片,JSON,Request的解析,但是总会有些数据不属于以上三种的,这时候就需要我们来自己实现的一个Request来解析我们需要的数据。

实现一个自定义的Request很简单:

1. 继承Request,T代表你要解析的类型,比如服务器返回的response是一个String,那么就要继承Request

2. 实现parseNetworkResponse()和deliverResponse()方法。

parseNetworkResponse

@Override
protected Response parseNetworkResponse(
        NetworkResponse response) {
    try {
        String json = new String(response.data,
        HttpHeaderParser.parseCharset(response.headers));
    return Response.success(gson.fromJson(json, clazz),
    HttpHeaderParser.parseCacheHeaders(response));
    }
    // handle errors
...
}


parseNetworkResponse()的参数NetworkResponse,这个参数中包含了HTTP的状态码,response的header等数据。我们重写这个函数时,返回的Response必须包含你类型化的返回对象,缓存的metadata或者一个error。

Volley是在一个新线程里调用parseNetworkResponse,防止主线程堵塞。


deliverResponse

Volley 在主线程中通过你在parseNetworkResponse()中返回的对象回调你。大多数的Request都会在这个方法触发一个回调接口,例如

protected void deliverResponse(T response) {
        listener.onResponse(response);


例子:GsonRequest

public class GsonRequest extends Request {
    private final Gson gson = new Gson();
    private final Class clazz;
    private final Map headers;
    private final Listener listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param clazz Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */
    public GsonRequest(String url, Class clazz, Map headers,
            Listener listener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

    @Override
    public Map getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}


你可能感兴趣的:(Android进阶,Android升级之路)