标签:android volley request 网络 gson
虽然Volley已经提供了对于String,图片,JSON,Request的解析,但是总会有些数据不属于以上三种的,这时候就需要我们来自己实现的一个Request来解析我们需要的数据。
实现一个自定义的Request很简单:
1. 继承Request<T>,T代表你要解析的类型,比如服务器返回的response是一个String,那么就要继承Request<String>
2. 实现parseNetworkResponse()和deliverResponse()方法。
@Override protected Response<T> 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<T>必须包含你类型化的返回对象,缓存的metadata或者一个error。
Volley是在一个新线程里调用parseNetworkResponse,防止主线程堵塞。
protected void deliverResponse(T response) { listener.onResponse(response);
<span style="font-size:14px;">public class GsonRequest<T> extends Request<T> { private final Gson gson = new Gson(); private final Class<T> clazz; private final Map<String, String> headers; private final Listener<T> 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<T> clazz, Map<String, String> headers, Listener<T> listener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.clazz = clazz; this.headers = headers; this.listener = listener; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers != null ? headers : super.getHeaders(); } @Override protected void deliverResponse(T response) { listener.onResponse(response); } @Override protected Response<T> 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)); } } }</span>
版权声明:本文为博主原创文章,转载请联系博主。
Android网络通信必备神器Volley详解——实现一个自定义的Request(以Gson为例)
标签:android volley request 网络 gson
原文地址:http://blog.csdn.net/l664675249/article/details/49847397