如何使用Volley

如何使用Volley

參考文件

ref link
github https://github.com/mcxiaoke/android-volley

簡介

由於HttpURLConnection和HttpClient用法過於複雜, 如果沒有進行適當的封裝, 容易寫出重覆的程式碼
因此Google推出Volley Http request framework來處理簡單的HTTP Request, 另外他也可以下載圖片, 不過對於下載多張圖片, 比較適合使用glide來處理,
volley是屬於輕量級的HTTP Request處理工具, 因此對於大量數據處理, 例如下載文件, 效能就沒有那麼理想。

如何使用

Gradle
compile 'com.mcxiaoke.volley:library:1.0.+'
初始化
取得volley的request物件,
建議將mQueue設為單一物件全域使用,避免浪費資源
RequestQueue mQueue = Volley.newRequestQueue(mContext);
GET
這邊StringRequest使用了三個參數
URL, 匿名Response處理以及匿名Error處理,
最後把這個request丟進queue即可
如果你把google網址網址丟進去 會看到回來一堆html tag
StringRequest getRequest = new StringRequest(YOUR_URL,
    new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {

        }
    },
    new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError volleyError) {

        }
    });
mQueue.add(getRequest);    
POST
如果你想要實作POST Request那麼必須自己覆寫getParams這個method
StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {  
    @Override  
    protected Map<String, String> getParams() throws AuthFailureError {  
        Map<String, String> map = new HashMap<String, String>();  
        map.put("params1", "value1");  
        map.put("params2", "value2");  
        return map;  
    }  
};  
PUT
String url = "PUT_URL";
StringRequest mStringRequest = new StringRequest(Request.Method.PUT,
        url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error
                Log.d("Error.Response", response);
            }
        }) {

    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", "mohammad_username");
        params.put("password", "mohammad_password");

        return params;
    }

};

mRequestQueue.add(mStringRequest);
DELETE
String url = "URL_DELETE";
StringRequest mStringRequest = new StringRequest(Request.Method.DELETE, url,
    new Response.Listener<String>()
    {
        @Override
        public void onResponse(String response) {
            // response
             Log.d("Response", response);
        }

    },
    new Response.ErrorListener()
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             Log.d("Error.Response", response);
       }
    }
);
mRequestQueue.add(mStringRequest);
如果你想要傳送JSON, 可以使用JsonObjectRequest
利用GSON將你的JSON打包
String postAPI = "http://jsonplaceholder.typicode.com/posts";

JsonStr mJsonStr = new JsonStr();
mJsonStr.setTitle("foo");
mJsonStr.setBody("bar");
mJsonStr.setUserId(1);
Gson gson = new Gson();
String json = gson.toJson(mJsonStr);

JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
        postAPI,
        json,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                new ShowDataDialog(MainActivity.this, response.toString()).show();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("err", error.toString());
            }
        }
);
mQueue.add(mJsonObjectRequest);
volley有cache機制
Cache mCache = AppController.getInstance().getRequestQueue().getCache();
Entry mEntry = mCache.get("URL");
if(entry != null){
    try {
        String cacheData = new String(mEntry.data, "UTF-8");
        // Convert the String to JSON , GSON and XML :D
    } catch (UnsupportedEncodingException e) {     
        e.printStackTrace();
        }
    }
}else{
    // Cached response doesn't exists. so you should Make network call here for non-cashed URL
}
如果不要cache可以關閉
// String request or JSON request.
StringRequest mStringRequest = new StringRequest(....);
// disable cache
mStringRequest.setShouldCache(false);
也可以將request從cache remove
mRequestQueue.getInstance().getRequestQueue().getCache().remove(url);
或者delete全部的cache
mRequestQueue.getInstance().getRequestQueue().getCache().clear(url);