Android working with Volley Library

Fooving發表於2014-06-29

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 queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

2、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);

 

3、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);

 

4、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);

 

5、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);

 

 

相關文章