Android開發(fā)中使用Volley庫發(fā)送HTTP請求的實例教程
Android Volley 是Google開發(fā)的一個網(wǎng)絡(luò)lib,可以讓你更加簡單并且快速的訪問網(wǎng)絡(luò)數(shù)據(jù)。Volley庫的網(wǎng)絡(luò)請求都是異步的,你不必?fù)?dān)心異步處理問題。
Volley的優(yōu)點:
- 請求隊列和請求優(yōu)先級
- 請求Cache和內(nèi)存管理
- 擴展性性強
- 可以取消請求
下載和編譯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到你的項目中
不過已經(jīng)有人將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工作原理圖

創(chuàng)建Volley 單例
使用volley時,必須要創(chuàng)建一個請求隊列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;
@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);
}
}
}
另外,你還需要一個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權(quán)限。
HTTP請求實例
private Context mContext;
private RequestQueue mRequestQueue;
private StringRequest mStringRequest;
// 利用Volley實現(xiàn)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("請求結(jié)果:" + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("請求錯誤:" + error.toString());
}
}) {
// 攜帶參數(shù)
@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 的頭信息。(也可不實現(xiàn))
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實現(xiàn)Json數(shù)據(jù)請求
private void volley_json() {
mContext = this;
String url = "http://aplesson.com/data/101010100.html";
// 1 創(chuàng)建RequestQueue對象
mRequestQueue = Volley.newRequestQueue(mContext);
// 2 創(chuàng)建JsonObjectRequest對象
mJsonObjectRequest = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println("請求結(jié)果:" + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("請求錯誤:" + error.toString());
}
});
// 3 將JsonObjectRequest添加到RequestQueue
mRequestQueue.add(mJsonObjectRequest);
}
// 利用Volley實現(xiàn)Get請求
private void volley_get() {
mContext = this;
String url = "http://www.aplesson.com/";
// 1 創(chuàng)建RequestQueue對象
mRequestQueue = Volley.newRequestQueue(mContext);
// 2 創(chuàng)建StringRequest對象
mStringRequest = new StringRequest(url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println("請求結(jié)果:" + 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,這樣可以自己處理數(shù)據(jù),更加靈活。
另外可以繼承Request<T>自定義Request。
取消Request
Activity里面啟動了網(wǎng)絡(luò)請求,而在這個網(wǎng)絡(luò)請求還沒返回結(jié)果的時候,Activity被結(jié)束了,此時如果繼續(xù)使用其中的Context等,除了無辜的浪費CPU,電池,網(wǎng)絡(luò)等資源,有可能還會導(dǎo)致程序crash,所以,我們需要處理這種一場情況。使用Volley的話,我們可以在Activity停止的時候,同時取消所有或部分未完成的網(wǎng)絡(luò)請求。Volley里所有的請求結(jié)果會返回給主進(jìn)程,如果在主進(jìn)程里取消了某些請求,則這些請求將不會被返回給主線程。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);
}
可以根據(jù)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等方法。
相關(guān)文章
Android仿微信列表滑動刪除 如何實現(xiàn)滑動列表SwipeListView
這篇文章主要為大家詳細(xì)介紹了Android仿微信列表滑動刪除,如何實現(xiàn)滑動列表SwipeListView,感興趣的小伙伴們可以參考一下2016-08-08
Android逆向入門之常見Davlik字節(jié)碼解析
Dalvik是Google公司自己設(shè)計用于Android平臺的虛擬機。Dalvik虛擬機是Google等廠商合作開發(fā)的Android移動設(shè)備平臺的核心組成部分之一,本篇文章我們來詳細(xì)解釋常見Davlik字節(jié)碼2021-11-11
Android開發(fā)學(xué)習(xí)筆記 淺談WebView
WebView(網(wǎng)絡(luò)視圖)能加載顯示網(wǎng)頁,可以將其視為一個瀏覽器。它使用了WebKit渲染引擎加載顯示網(wǎng)頁,實現(xiàn)WebView有以下兩種不同的方法2014-11-11
Android圖片翻轉(zhuǎn)動畫簡易實現(xiàn)代碼
Android圖片翻轉(zhuǎn)動畫效果如何實現(xiàn),本文將給你一個驚喜,實現(xiàn)代碼已經(jīng)列出,需要的朋友可以參考下2012-11-11
Android應(yīng)用中ListView利用OnScrollListener分頁加載數(shù)據(jù)
這篇文章主要介紹了Android應(yīng)用中ListView利用OnScrollListener分頁加載數(shù)據(jù)的方法,包括對OnScrollListener事件順序次數(shù)的分析,需要的朋友可以參考下2016-03-03
Android開發(fā)中使用Intent打開第三方應(yīng)用及驗證可用性的方法詳解
這篇文章主要介紹了Android開發(fā)中使用Intent打開第三方應(yīng)用及驗證可用性的方法,結(jié)合實例形式分析了Android使用Intent打開第三方應(yīng)用的三種常用方式及使用注意事項,需要的朋友可以參考下2017-11-11

