使用Android studio在build.gradle添加以下信息就可以获取支持库,当然了,如果你没有下载到该支持库会提示你下载。
compile 'com.mcxiaoke.volley:library:1.0.19'
在一个Application中创建一个请求队列,调用通过((Myapp) getApplication()).requestQueue.add(request);
public RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate();
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
有多种请求队列,这里就不再叙述,主要写一个自定义的请求队列
public class ObjectRequest<T> extends Request {
private final Response.Listener surcess;
private final Class<T> cls;
public ObjectRequest(int method, String url,
Response.ErrorListener listener,
Response.Listener surcess,
Class<T> cls) {
super(method, url, listener);
this.surcess = surcess;
this.cls = cls;
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
String result = null;
try {
//设置响应后返回值的编码,与服务器请求头的一致
result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
//解析
Gson gson = new Gson();
T t = gson.fromJson(result, cls);
return Response.success(t, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new VolleyError(e));
}
}
/**
* @param response
*/
@Override
protected void deliverResponse(Object response) {
if (surcess != null) {//Response.Listener 响应的监听为空。。
surcess.onResponse(response);
}
}
}
--Zero
Android Volley运用
点赞
收藏