Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Volley 入門教學:Android 網路請求庫的常用用法整理

編輯:關於 Android 程式設計

以前做 API 連線,GET、POST 這些操作大多直接靠 Android 內建的類別硬寫,程式碼又長又不好維護。後來想著換一套好用的 library,應該能事半功倍,於是挑了三套社群討論度比較高的方案來評估:

  1. Android Asynchronous Http Client
  2. okhttp:Square 開發並開源的專案。因為之前用過他們家的 Picasso,對這一套原本頗有好感,只可惜呼叫方式不太合自己的胃口。
  3. Volley:Google 在 2013 年 Google I/O 上發表,至今累積了很高的人氣。

專案網址:https://github.com/mcxiaoke/android-volley

建立 JSON 請求

Volley 內建了 JsonObjectRequest 與 JsonArrayRequest,分別負責 JSON 物件與 JSON 陣列類型的請求。值得一提的是,Volley 並沒有提供基於 Gson 的 GsonRequest(也就是發出一個 request、直接拿到一個 Java 物件),不過這部分我們可以自己動手包裝。

建立物件請求的寫法相當直觀:new 一個 Request 物件、實作回呼介面,再把請求丟進請求佇列即可,陣列請求也是同樣套路。

 // Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "https://api.androidhive.info/volley/person_object.json"; JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); 

建立字串請求

StringRequest 幾乎什麼都能抓:JSON、XML、純文字都適用,泛用性最高。

 // Tag used to cancel the request String tag_string_req = "string_req"; String url = "https://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); 

建立 POST 請求

前面示範的都是 GET,POST 的差别其實只有兩處:把請求方法改成 POST,然後覆寫 getParams() 把參數帶上去。

 // Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "https://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); 

加上自訂的 Request Header

需要帶 token、apiKey 或指定 Content-Type 時,覆寫 getHeaders() 就好。

 // Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "https://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); 

載入圖片

Volley 附了一個 NetworkImageView,可以直接用它來抓圖,省下不少工。

1. 用 NetworkImageView 載入

先講原理:NetworkImageView 只需要一個 ImageLoader 和一個圖片網址,而 ImageLoader 又依賴一組請求佇列與一個 ImageCache。呼叫 setImageUrl() 之後,它會先比對目前 ImageView 上的網址跟新傳進來的網址是否相同;相同就不重送請求,不同才透過 ImageLoader 發出 HTTP 連線。

 ImageLoader imageLoader = AppController.getInstance().getImageLoader(); // If you are using NetworkImageView imgNetWorkView.setImageUrl(Const.URL_IMAGE, imageLoader); 

2. 用一般 ImageView 載入

做法與上面類似,只是改成透過 ImageLoader 的 get() 回呼取得 Bitmap。

 ImageLoader imageLoader = AppController.getInstance().getImageLoader(); // If you are using normal ImageView imageLoader.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 response, boolean arg1) { if (response.getBitmap() != null) { // load image into imageview imageView.setImageBitmap(response.getBitmap()); } } }); 

想再偷懶一點,可以直接用現成的 listener,順便把佔位圖與錯誤圖一起指定:

 // Loading image with placeholder and error image imageLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(imageView, R.drawable.ico_loading, R.drawable.ico_error));

Volley 的快取機制

Volley 內建了一套相當完整的 cache 機制來管理請求結果,能有效減少網路往返次數,也縮短使用者等待的時間。要直接從快取把資料取出來:

 Cache cache = AppController.getInstance().getRequestQueue().getCache(); Entry entry = cache.get(url); if(entry != null){ try { String data = new String(entry.data, "UTF-8"); // handle data, like converting it to xml, json, bitmap etc., } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }else{ // Cached response doesn't exists. Make network call here } 

讓快取失效:這裡的「失效」並不是刪除,Volley 仍會沿用舊的快取內容,直到伺服器回來的新資料把它覆蓋為止。

 AppController.getInstance().getRequestQueue().getCache().invalidate(url, true); 

關閉單一請求的快取:直接對該 Request 呼叫 setShouldCache(false)。

 // String request StringRequest stringReq = new StringRequest(....); // disable cache stringReq.setShouldCache(false); 

刪除指定網址的快取:

 AppController.getInstance().getRequestQueue().getCache().remove(url); 

清空所有快取:

 AppController.getInstance().getRequestQueue().getCache().clear(); 

取消請求

addToRequestQueue(request, tag) 的第二個參數就是標記用的 tag。替同一類請求打上同一個 tag,之後就能一次全部取消,例如離開頁面時清掉殘留的請求。

 String tag_json_arry = "json_req"; ApplicationController.getInstance().getRequestQueue().cancelAll("feed_request"); 

設定請求優先級

覆寫 getPriority() 即可指定優先順序,共有 Normal、Low、Immediate、High 四種。

 private Priority priority = Priority.HIGH; StringRequest strReq = new StringRequest(Method.GET, Const.URL_STRING_REQ, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response.toString()); msgResponse.setText(response.toString()); hideProgressDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); hideProgressDialog(); } }) { @Override public Priority getPriority() { return priority; } };
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved