Android開發中使用Volley庫發送HTTP請求的執行個體教程_Android

來源:互聯網
上載者:User

Android Volley 是Google開發的一個網路lib,可以讓你更加簡單並且快速的訪問網路資料。Volley庫的網路請求都是非同步,你不必擔心非同步處理問題。
Volley的優點:

  • 請求隊列和請求優先順序
  • 請求Cache和記憶體管理
  • 擴充性性強
  • 可以取消請求

下載和編譯volley.jar
需要安裝git,ant,android sdk
clone代碼:

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

編譯jar:

android update project -p . ant jar

添加volley.jar到你的項目中
不過已經有人將volley的代碼放到github上了:
https://github.com/mcxiaoke/android-volley,你可以使用更加簡單的方式來使用volley:
Maven
format: jar

<dependency>  <groupId>com.mcxiaoke.volley</groupId>  <artifactId>library</artifactId>  <version>1.0.6</version></dependency>

Gradle
format: jar

compile 'com.mcxiaoke.volley:library:1.0.6'

Volley工作原理圖

建立Volley 單例
使用volley時,必須要建立一個請求隊列RequestQueue,使用請求隊列的最佳方式就是將它做成一個單例,整個app使用這麼一個請求隊列。

public class AppController extends Application {public static final String TAG = AppController.class    .getSimpleName();private RequestQueue mRequestQueue;private ImageLoader mImageLoader;private static AppController mInstance;@Overridepublic 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);  }}}

另外,你還需要一個Cache來存放請求的圖片:

public class LruBitmapCache extends LruCache<String, Bitmap> implement ImageCache {  public static int getDefaultLruCacheSize() {    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);    final int cacheSize = maxMemory / 8;    return cacheSize;  }  public LruBitmapCache() {    this(getDefaultLruCacheSize());  }  public LruBitmapCache(int sizeInKiloBytes) {    super(sizeInKiloBytes);  }  @Override  protected int sizeOf(String key, Bitmap value) {    return value.getRowBytes() * value.getHeight() / 1024;  }  @Override  public Bitmap getBitmap(String url) {    return get(url);  }  @Override  public void putBitmap(String url, Bitmap bitmap) {    put(url, bitmap);  }}

別忘記在AndroidManifest.xml檔案中添加android.permission.INTERNET許可權。

HTTP請求執行個體

  private Context mContext;  private RequestQueue mRequestQueue;  private StringRequest mStringRequest;  // 利用Volley實現Post請求  private void volley_post() {    String url = "http://aplesson.com/wap/api/user.php?action=login";    mContext = this;    mRequestQueue = Volley.newRequestQueue(mContext);    mStringRequest = new StringRequest(Method.POST, url,        new Response.Listener<String>() {          @Override          public void onResponse(String response) {            System.out.println("請求結果:" + response);          }        }, new Response.ErrorListener() {          @Override          public void onErrorResponse(VolleyError error) {            System.out.println("請求錯誤:" + error.toString());          }        }) {      // 攜帶參數      @Override      protected HashMap<String, String> getParams()          throws AuthFailureError {        HashMap<String, String> hashMap = new HashMap<String, String>();        hashMap.put("un", "852041173");        hashMap.put("pw", "852041173abc");        return hashMap;      }      // Volley請求類提供了一個 getHeaders()的方法,重載這個方法可以自訂HTTP 的頭資訊。(也可不實現)      public Map<String, String> getHeaders() throws AuthFailureError {        HashMap<String, String> headers = new HashMap<String, String>();        headers.put("Accept", "application/json");        headers.put("Content-Type", "application/json; charset=UTF-8");        return headers;      }    };    mRequestQueue.add(mStringRequest);  }  private JsonObjectRequest mJsonObjectRequest;  // 利用Volley實現Json資料請求  private void volley_json() {    mContext = this;    String url = "http://aplesson.com/data/101010100.html";    // 1 建立RequestQueue對象    mRequestQueue = Volley.newRequestQueue(mContext);    // 2 建立JsonObjectRequest對象    mJsonObjectRequest = new JsonObjectRequest(url, null,        new Response.Listener<JSONObject>() {          @Override          public void onResponse(JSONObject response) {            System.out.println("請求結果:" + response.toString());          }        }, new Response.ErrorListener() {          @Override          public void onErrorResponse(VolleyError error) {            System.out.println("請求錯誤:" + error.toString());          }        });    // 3 將JsonObjectRequest添加到RequestQueue    mRequestQueue.add(mJsonObjectRequest);  }  // 利用Volley實現Get請求  private void volley_get() {    mContext = this;    String url = "http://www.aplesson.com/";    // 1 建立RequestQueue對象    mRequestQueue = Volley.newRequestQueue(mContext);    // 2 建立StringRequest對象    mStringRequest = new StringRequest(url,        new Response.Listener<String>() {          @Override          public void onResponse(String response) {            System.out.println("請求結果:" + response);          }        }, new Response.ErrorListener() {          @Override          public void onErrorResponse(VolleyError error) {            System.out.println("請求錯誤:" + error.toString());          }        });    // 3 將StringRequest添加到RequestQueue    mRequestQueue.add(mStringRequest);  }


Volley提供了JsonObjectRequest、JsonArrayRequest、StringRequest等Request形式。JsonObjectRequest:返回JSON對象。
JsonArrayRequest:返回JsonArray。
StringRequest:返回String,這樣可以自己處理資料,更加靈活。
另外可以繼承Request<T>自訂Request。

取消Request
Activity裡面啟動了網路請求,而在這個網路請求還沒返回結果的時候,Activity被結束了,此時如果繼續使用其中的Context等,除了無辜的浪費CPU,電池,網路等資源,有可能還會導致程式crash,所以,我們需要處理這種一場情況。使用Volley的話,我們可以在Activity停止的時候,同時取消所有或部分未完成的網路請求。Volley裡所有的請求結果會返回給主進程,如果在主進程裡取消了某些請求,則這些請求將不會被返回給主線程。Volley支援多種request取消方式。
可以針對某些個request做取消操作:

 @Override  public void onStop() {    for (Request <?> req : mRequestQueue) {      req.cancel();    }  }

取消這個隊列裡的所有請求:

 @Override  protected void onStop() {    // TODO Auto-generated method stub    super.onStop();    mRequestQueue.cancelAll(this);  }

可以根據RequestFilter或者Tag來終止某些請求

 @Override  protected void onStop() {    // TODO Auto-generated method stub    super.onStop();    mRequestQueue.cancelAll( new RequestFilter() {});    or    mRequestQueue.cancelAll(new Object());  }

Volley支援http的GET、POST、PUT、DELETE等方法。


聯繫我們

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