Android working with Volley Library

來源:互聯網
上載者:User

標籤:android   style   blog   http   color   使用   

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

Volley提供的功能

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

1、封裝了的非同步RESTful 請求API;

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

3、一個可擴充的架構,它使開發人員能夠實現自訂的請求和響應處理機制;

4、能夠使用外部HTTP Client庫;

5、緩衝策略;

6、自訂的網狀圖像載入視圖(NetworkImageView,ImageLoader等);

 

為什麼使用非同步HTTP請求?

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

 

怎樣使用Volley

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

1、安裝和使用Volley庫

2、使用請求隊列

3、非同步JSON、String請求

4、取消請求

5、重試失敗的請求,自訂請求逾時

6、佈建要求頭(HTTP headers)

7、使用Cookies

8、錯誤處理

安裝和使用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);        }    }}

 

 

1、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 queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

2、Making json array request

// Tag used to cancel the requestString 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 queueAppController.getInstance().addToRequestQueue(req, tag_json_arry);

 

3、Making String request

// Tag used to cancel the requestString  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 queueAppController.getInstance().addToRequestQueue(strReq, tag_string_req);

 

4、Adding post parameters

// Tag used to cancel the requestString 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", "[email protected]");                params.put("password", "password123");                 return params;            }         }; // Adding request to request queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

5、Adding request headers

// Tag used to cancel the requestString 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 queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.