1使用Android studio在build.gradle添加以下信息就可以获取支持库,当然了,如果你没有下载到该支持库会提示你下载。 2 3 4compile 'com.mcxiaoke.volley:library:1.0.19' 5 6在一个Application中创建一个请求队列,调用通过((Myapp) getApplication()).requestQueue.add(request); 7 8 9 10public RequestQueue requestQueue; 11 12@Override 13public void onCreate() { 14 super.onCreate(); 15 requestQueue = Volley.newRequestQueue(getApplicationContext()); 16} 17 18有多种请求队列,这里就不再叙述,主要写一个自定义的请求队列 19 20 21public class ObjectRequest<T> extends Request { 22 private final Response.Listener surcess; 23 private final Class<T> cls; 24 25 26 public ObjectRequest(int method, String url, 27 Response.ErrorListener listener, 28 Response.Listener surcess, 29 Class<T> cls) { 30 super(method, url, listener); 31 this.surcess = surcess; 32 this.cls = cls; 33 } 34 35 @Override 36 protected Response parseNetworkResponse(NetworkResponse response) { 37 String result = null; 38 try { 39 //设置响应后返回值的编码,与服务器请求头的一致 40 result = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 41 //解析 42 Gson gson = new Gson(); 43 T t = gson.fromJson(result, cls); 44 return Response.success(t, HttpHeaderParser.parseCacheHeaders(response)); 45 } catch (UnsupportedEncodingException e) { 46 return Response.error(new VolleyError(e)); 47 } 48 } 49 /** 50 * @param response 51 */ 52 @Override 53 protected void deliverResponse(Object response) { 54 if (surcess != null) {//Response.Listener 响应的监听为空。。 55 surcess.onResponse(response); 56 } 57 } 58} 59 60 61--Zero
Android Volley运用
Stella981
2021-10-11
1043 0 0
点赞
收藏
评论区
加载中...