Volley

Volley 相关的使用方法:

首先创建一个AppController 类

再创建一个图片缓存的LruBitmapCache类:

  1. 创建一个AppController 类

    public class AppController extends Application{

    public static final String TAG = AppController.class.getSimpleName();
    
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    
    private static AppController mInstance;
    
    @Override
    public void onCreat(){
        super.onCreat();
        mInstance = this;
    }
    
    public static synchroinzed AppController getInstance(){
        return mInstance;
    }
    
    public RequestQueue getRequestQueue(){
        if(mInstance == null){
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }
    
    public ImageLoader getImageLoader(){
        getRequestQueue();
    
        if(mImageLoader == null){
            mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
        }
        return this.mImageLoader;
    }
    
    public <T> void addToRequestQueue(Request<T> req, String tag){
        req.setTag(TextUtil.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
    
    public void cancelPendingRequests(Object tag){
        if(mRequestQueue != null){
            mRequestQueue.cancelAll(tag);
        }
    }
    

    }

  2. 创建一个图片缓存的LruBitmapCache类

    public class LruBitmapCache extends LruCache<String, Bitmap> implement ImageCache{
        public static int getDefaultLruCacheSize(){
            final int maxMemory = (int) (Runtime.getRuntime().maxMemory / 1034);
            final int cacheSize = maxMemory / 8;
    
            return cacheSize;
        }
    
        public LruBitmapCache(){
            this(getDefaultLruCacheSize());
        }
    
        public LruBitmapCache(int sizeInkiloBytes){
            super(sizeInkiloBytes);
        }
    
        @Override
        protected int sizeOf(String key, Bitmap value){
            return value.getRowBytes() * value.getHeight() / 1024;
        }
    
        @Override
        public Bitmap getBitmap(String url){
            return get(url);
        }
    
        @Override
        public void putBitmap(String url, Bitmap bitmap){
            put(url, bitmap);
        }
    }
    
  3. 各类函数对以上两个方法的调用来获取所需的网络数据

    public void JsonFun(){
    
        String tag_json_obj = "json_obj_req";
        String url = "http://api.androidhive.info/volley/person_object.json";
    
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null,
                        new Response.Listener<JSONObject>(){
    
                            @Override
                            public void onResponse(JSONObject reponse){
                                Log.d(TAG, reponse.toString());
                            }
                        }, new Response.ErrorListener(){
    
                            @Override
                            public void onErrorResponse(VolleyError error){
                                VolleyLog.d(TAG, "Error:" + error.getMessage());
                            }
                        });
    
        AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
    
    }
    
public void StringFun(){
    String tag_string_req = "string_req";
    String url = "";

    ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();

    StringRequest strReq = new StringRequest(Method.GET,
                url, new Response.Listener<String>(){
                    Log.d(TAG, reponse.toString());
                    pDialog.hide();
                }, new Response.ErrorListener(){

                    @Override
                    public void onErrorResponse(VolleyError error){
                        VolleyLog.d(TAG, "Error:" + error.getMessage);
                        pDialog.hide();
                    }
                });
    AppController.getInstance.addToRequestQueue(strReq, tag_string_req);
}

Post请求:

public void PostFun(){
    String tag_json_obj = "json_obj_req";

    String url = "";
    ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, null,
                new Response.Listener<JSONObject>(){

                @Override
                public void onResponse(JSONObject reponse){
                    Log.d(TAG, reponse.toString());
                    pDialog.hide();
                }
            }, new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    VolleyLog.d(TAG, "Error:" + error.getMessage());
                    pDialog.hide();
                }
            }){
        @Override
        protected Map<String, String> getParams(){
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", "Androidhive");
            params.put("email", "abc@androidhive.info");
            params.put("password", "password123");

            return params;
        }

    };

    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

请求图片的函数:

public void setImageFun(){
    ImageLoader imgLoader = AppController.getInstance().getImageLoader();

    //复杂写法
    imgLoader.get(Const.URL_IMAGE, new ImageListener(){
        @Override
        public void onErrorResponse(VolleyError error){
            Log.e(TAG, "Image Load Error:" + error.getMessage());
        }

        @Override
        public void onResponse(ImageContainer reponse, boolean arg1){
            if(reponse.getBitmap() != null){
                //load image into imageview
                imageview.setImageBitemap(reponse.getBitmap());
            }
        }
    });

    //简便写法
    imgLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(imageview, imageView, R.drawable.ico_loading, R.drawable.ico_error));
}

关于Cache:

public void volleyCacheFun(){
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(url);

    if(entry != null){
        try{
            String data = new String(entry.data, "UTF-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
    } else {
        // Cached response doesn't exists. Make network call here
    }
}

//刷新页面
App.getInstance().getRequestQueue().getCache().invalidate(u, true);

//关闭cache
//String request
StringRequest stringReq = new StringRequest(...);

//disable cache
stringReq.setShouldCache(false);

//删除某个URL的Cache
AppController.getInstance().getRequestQueue().getCache().remove(url);

//删除所有的cache
AppController.getInstance().getRequestQueue().getCache().clear();

//取消请求
String tag_json_arry = "json_req";
AppController.getInstance().getRequestQueue().cancelAll("feed_request");

设置请求的优先级:

public void requestPriorityFun(){
    private Priority priority = PostFun.HIGH;

    StringRequest strReq = new StringRequest(Method.GET,
                Const.URL_STRING_REQ, new Response.Listener<String>(){

                    @Override
                    public void onResponse(String reponse){
                        Log.d(TAG, reponse.toString());
                        msgResponse.setText(reponse,toString());
                        hideProgressDialog();
                    }
                }, new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error){
                        VolleyLog.d(TAG, "Error:" + error.getMessage());
                        hideProgressDialog();
                    }
                }){
            @Override
            public Priority getPriority(){
                return priority;
            }
        };
}

添加请求头部信息:

public void addHeadFun(){
    String tag_json_obj = "json_obj_req";
    String url = "";
    ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading");
    pDialog.show();
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, null, new Response.Listener<JSONObject>(){
        @Override
        public void onResponse(JSONObject reponse){
            Log.d(TAG, reponse.toString());
            pDialog.hide();
        }
    }, new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError error){
            VolleyLog.d(TAG, "Error:" + error.getMessage());
            pDialog.hide();
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError{
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("apiKey", "********");
            return headers;
        }
    };
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}