Android working with Volley Library

Volley提供了優美的框架,使得Android應用程序網絡訪問更容易和更快。Volley抽象實現了底層的HTTP Client庫,讓你不關注HTTP Client細節,專一於寫出更加漂亮、乾淨的RESTful HTTP請求。另外,Volley請求會異步執行,不阻擋主線程。html

Volley提供的功能android

簡單的講,提供了以下主要的功能:git

一、封裝了的異步的RESTful 請求API;json

二、一個優雅和穩健的請求隊列;api

三、一個可擴展的架構,它使開發人員可以實現自定義的請求和響應處理機制;緩存

四、可以使用外部HTTP Client庫;網絡

五、緩存策略;架構

六、自定義的網絡圖像加載視圖(NetworkImageView,ImageLoader等);app

 

爲何使用異步HTTP請求?框架

Android中要求HTTP請求異步執行,若是在主線程執行HTTP請求,可能會拋出android.os.NetworkOnMainThreadException  異常。阻塞主線程有一些嚴重的後果,它阻礙UI渲染,用戶體驗不流暢,它可能會致使可怕的ANR(Application Not Responding)。要避免這些陷阱,做爲一個開發者,應該始終確保HTTP請求是在一個不一樣的線程。

 

怎樣使用Volley

這篇博客將會詳細的介紹在應用程程中怎麼使用volley,它將包括一下幾方面:

一、安裝和使用Volley庫

二、使用請求隊列

三、異步的JSON、String請求

四、取消請求

五、重試失敗的請求,自定義請求超時

六、設置請求頭(HTTP headers)

七、使用Cookies

八、錯誤處理

安裝和使用Volley庫

引入Volley很是簡單,首先,從git庫先克隆一個下來:

git clone https://android.googlesource.com/platform/frameworks/volley

而後編譯爲jar包,再把jar包放到本身的工程的libs目錄。

 

Creating Volley Singleton class

import info.androidhive.volleyexamples.volley.utils.LruBitmapCache;
import android.app.Application;
import android.text.TextUtils;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
 
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 onCreate() {
        super.onCreate();
        mInstance = this;
    }
 
    public static synchronized AppController getInstance() {
        return mInstance;
    }
 
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == 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) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
 
    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
 
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

 

 

一、Making json object request

String url = "";
         
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();     
         
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {
 
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        // hide the progress dialog
                        pDialog.hide();
                    }
                });
 
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

二、Making json array request

// Tag used to cancel the request
String tag_json_arry = "json_array_req";
 
String url = "http://api.androidhive.info/volley/person_array.json";
         
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();     
         
JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());        
                        pDialog.hide();             
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                });
 
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_arry);

 

三、Making String request

// Tag used to cancel the request
String  tag_string_req = "string_req";
 
String url = "http://api.androidhive.info/volley/string_response.html";
         
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();     
         
StringRequest strReq = new StringRequest(Method.GET,
                url, new Response.Listener<String>() {
 
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
 
                    }
                }, new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                });
 
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

 

四、Adding post parameters

// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
 
String url = "http://api.androidhive.info/volley/person_object.json";
         
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 response) {
                        Log.d(TAG, response.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;
            }
 
        };
 
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

五、Adding request headers

// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
 
String url = "http://api.androidhive.info/volley/person_object.json";
         
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 response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {
 
            /**
             * Passing some request headers
             * */
            @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", "xxxxxxxxxxxxxxx");
                return headers;
            }
 
        };
 
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
相關文章
相關標籤/搜索