Android的HTTP操作庫Volley的基本使用教程_Android

來源:互聯網
上載者:User

以前原本都用android內建的Library來進行GET、POST等等對API的連線與操作。
但最近想說來找找看有沒有好用的library,應該可以事半功倍。
當初有找了三套比較多人用的
1.Android Asynchronous Http Client
2.okhttp
square開發並且開源的,因為之前用過他們家的picasso,所以對這套滿有好感的,只可惜使用方式不太喜歡
3.Volley
Volley是Google在2013年Google I/O的時候發布的,到現在已經積累了很高的人氣。
Volley的GitHub項目地址:https://github.com/mcxiaoke/android-volley

建立Json請求
volley內建了JsonObjectRequest和JsonArrayRequest分別來處理Json對象請求和Json資料請求(但是voley沒有使用gson庫寫一個GsonRequest,發送一個request,volley直接返回一個java對象,不過我們可以自己寫)。
建立json object請求。
發送一個請求只要這麼簡單,建立一個JsonRequest對象,寫好response回調介面,並把這個請求放到請求隊列中就可以了。JsonArrayRequest也類似。

// Tag used to cancel the requestString tag_json_obj = "json_obj_req";String url = "http://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 queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

建立String請求
StringRequest可以用來請求任何string類型的資料:json,xml,文本等等。

// 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);

建立POST請求
上面說的都是GET請求,下面來說一下POST請求,與GET請求不同的是,只要在建立請求的時候將請求類型改為POST請求,並且override Request的getParams方法即可。

// 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", "abc@androidhive.info");      params.put("password", "password123");      return params;    }  };// Adding request to request queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

添加要求標頭部資訊

// 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* */@Overridepublic 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);

建立Image請求
Volley庫中內建了NetworkImageView類,這個ImageView可以自動使用volley下載圖片
1.用NetworkImageView載入圖片
首先,說明一下,載入圖片的原理:
NetworkImageView載入圖片需要一個ImageLoader和一個圖片URL,這個ImageLoader對象需要一個請求隊列對象和ImageCahe對象。調用NetworkImageView的setUrl方法後,首先會判斷當前ImageView的URL和新傳入的URL是否一致,如果相同,就不用再發送http請求了,如果不同,那麼就使用ImageLoader對象來發送http請求擷取圖片。

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

載入一個圖片只要這麼簡單~~~
2.用ImageView來載入圖片
這個過程和NetworkImageView類似

ImageLoader imageLoader = AppController.getInstance().getImageLoader();// If you are using normal ImageViewimageLoader.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());    }  }});

可以再簡單一點:

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


ImageLoader.getImageListener方法中已經寫了一個預設的ImageListener了
Volley Cache
volley中內建了強大的cache機制來管理請求cache,這會減少網路請求次數和使用者等待時間。
從請求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);

關閉Cache
如果你想將某一個請求的Cache功能關閉,直接調用Request的setShouldCache()方法就可以:

// String requestStringRequest stringReq = new StringRequest(....);// disable cachestringReq.setShouldCache(false);

將某一URL的Cache刪除
調用Cache的remove方法可以刪除這個URL的cache:

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

刪除所有的Cache

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

取消請求
在你添加一個請求到請求隊列中的時候,你可以發現,addToRequestQueue(request, tag)方法還接受一個tag參數,這個tag就是用來標記某一類請求的,這樣就可以取消這個tag的所有請求了:

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

請求優先順序
在建立一個request的時候可以Override 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;    }  };

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.