在Android開發(fā)中不可避免地需要用到網(wǎng)絡(luò)訪問辫愉,多數(shù)情況下會使用HTTP協(xié)議來發(fā)送和接收網(wǎng)絡(luò)數(shù)據(jù)墨榄。Android系統(tǒng)中主要提供了兩種方式來進(jìn)行HTTP通信:HttpURLConnection和HttpClient草冈。
HttpURLConnection和HttpClient的用法還是稍微有些復(fù)雜,如果沒有進(jìn)行封裝的話停局,很容易寫出不少重復(fù)代碼稚茅。這時就出現(xiàn)很多Android網(wǎng)絡(luò)通信框架,比如AsyncHttpClient袱院,它把HTTP所有的通信細(xì)節(jié)全部封裝在了內(nèi)部屎慢,我們只需要簡單調(diào)用幾行代碼就可以完成通信操作了瞭稼。比如Universal-Image-Loader,它使得在界面上顯示網(wǎng)絡(luò)圖片的操作變得極度簡單腻惠,因?yàn)閁niversal-Image-Loader已經(jīng)把一切都做好了环肘,我們不用關(guān)心如何從網(wǎng)絡(luò)上獲取圖片,也不用關(guān)心開啟線程妖枚、回收圖片資源等廷臼。
而當(dāng)前十分熱門的Volley網(wǎng)絡(luò)框架,也是在2013年Google I/O大會上推出了一個新的網(wǎng)絡(luò)通信框架绝页。Volley把AsyncHttpClient和Universal-Image-Loader的優(yōu)點(diǎn)集于了一身荠商,既可以像AsyncHttpClient一樣非常簡單地進(jìn)行HTTP通信,也可以像Universal-Image-Loader一樣輕松加載網(wǎng)絡(luò)上的圖片续誉。
本身已有良好封裝的Volley確實(shí)給程序開發(fā)帶來了很多便利與快捷莱没,但我們?nèi)匀豢梢詫olley進(jìn)行二次封裝。
由于需要用到網(wǎng)絡(luò)訪問酷鸦,所以不要忘記添加權(quán)限哦
<uses-permission android:name="android.permission.INTERNET" />
首先我們創(chuàng)建一個類繼承Application并在AndroidManifest.xml文件中的application標(biāo)簽中進(jìn)行注冊饰躲,在我們創(chuàng)建的Application中通過Volley.newRequestQueue(getApplicationContext())獲取 RequestQueue對象。
package com.xiaolijuan.volleydome;
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
/**
* @author: xiaolijuan
* @description:
* @date: 2016-03-11
* @time: 11:34
*/
public class AppApplication extends Application {
public static RequestQueue queues;
@Override
public void onCreate() {
super.onCreate();
queues = Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getHttpQueues() {
return queues;
}
}
HttpUtils.java
package com.xiaolijuan.volleydome.network;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.xiaolijuan.volleydome.AppApplication;
import java.util.Map;
/**
* @author: xiaolijuan
* @description: 使用Volley訪問Http請求管理的工具類
* @date: 2016-03-15
* @time: 15:39
*/
public class HttpUtils {
public static StringRequest stringRequest;
/**
* Get請求臼隔,獲得返回?cái)?shù)據(jù)
*
* @param context 上下文
* @param url 發(fā)送請求的URL
* @param tag TAG標(biāo)簽
* @param vif 請求回調(diào)的接口(請求成功或者失斷诹选)
*/
public static void doGet(Context context, String url, String tag, VolleyInterface vif) {
Log.e("發(fā)送Get請求的URL:", url);
//獲取全局的請求隊(duì)列并把基于Tag標(biāo)簽的請求全部取消,防止重復(fù)請求
AppApplication.getHttpQueues().cancelAll(tag);
//實(shí)例化StringRequest
stringRequest = new StringRequest(Method.GET, url, vif.loadingListener(), vif.errorListener());
// 設(shè)置標(biāo)簽
stringRequest.setTag(tag);
// 將請求添加至隊(duì)列里面
AppApplication.getHttpQueues().add(stringRequest);
// 啟動
AppApplication.getHttpQueues().start();
}
/**
* 向指定 URL 發(fā)送POST方法的請求
*
* @param context 上下文
* @param url 發(fā)送請求的URL
* @param tag TAG標(biāo)簽
* @param params 請求參數(shù)摔握,請求參數(shù)應(yīng)該是Hashmap類型
* @param vif 請求回調(diào)的接口(請求成功或者失敿睦恰)
*/
public static void doPost(Context context, String url, String tag, final Map<String, String> params,
VolleyInterface vif) {
Log.e("發(fā)送Get請求的URL:", url);
//獲取全局的請求隊(duì)列并把基于Tag標(biāo)簽的請求全部取消,防止重復(fù)請求
AppApplication.getHttpQueues().cancelAll(tag);
stringRequest = new StringRequest(url, vif.loadingListener(), vif.errorListener()) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
// 設(shè)置標(biāo)簽
stringRequest.setTag(tag);
// 加入隊(duì)列
AppApplication.getHttpQueues().add(stringRequest);
// 啟動
AppApplication.getHttpQueues().start();
}
}
VolleyInterface.java
package com.xiaolijuan.volleydome.network;
import android.content.Context;
import android.util.Log;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
/**
* @author: xiaolijuan
* @description: 請求成功或失敗的接口回調(diào)
* @date: 2016-03-15
* @time: 15:39
*/
public abstract class VolleyInterface {
/**
* 上下文
*/
public Context mContext;
/**
* 請求成功監(jiān)聽
*/
public static Listener<String> mListener;
/**
* 請求失敗監(jiān)聽
*/
public static ErrorListener mErrorListtener;
public VolleyInterface(Context context, Listener<String> listener, ErrorListener errorListener) {
this.mContext = context;
this.mListener = listener;
this.mErrorListtener = errorListener;
}
/**
* 請求成功的抽象類
*
* @param result
*/
public abstract void onSuccess(String result);
/**
* 請求失敗的抽象類
*
* @param error
*/
public abstract void onError(VolleyError error);
/**
* 請求成功監(jiān)聽
*
* @return
*/
public Listener<String> loadingListener() {
mListener = new Listener<String>() {
@Override
public void onResponse(String result) {
Log.e("請求成功返回的數(shù)據(jù):", result);
onSuccess(result);
}
};
return mListener;
}
/**
* 請求失敗監(jiān)聽
*
* @return
*/
public ErrorListener errorListener() {
mErrorListtener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("請求失敗返回的數(shù)據(jù):", error.toString());
onError(error);
}
};
return mErrorListtener;
}
}
由于代碼寫得很詳細(xì)氨淌,我這里就不再一一解釋啦
package com.xiaolijuan.volleydome;
import android.app.Activity;
import android.os.Bundle;
import com.android.volley.VolleyError;
import com.xiaolijuan.volleydome.network.HttpUtils;
import com.xiaolijuan.volleydome.network.VolleyInterface;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doGet();
}
private void doGet() {
String url = "";
String tag = "GET";
HttpUtils.doGet(getApplicationContext(), url, tag,
new VolleyInterface(getApplicationContext(), VolleyInterface.mListener, VolleyInterface.mErrorListtener) {
@Override
public void onSuccess(String result) {
}
@Override
public void onError(VolleyError error) {
}
});
}
/**
* volley和activity的關(guān)聯(lián)
*/
@Override
protected void onStop() {
super.onStop();
// 在停止的時候也把tag標(biāo)簽的網(wǎng)絡(luò)請求給停掉
AppApplication.getHttpQueues().cancelAll("");
}
}
本篇博客在這里就結(jié)束了泊愧,有不足的地方還望各路大神指導(dǎo) ,謝謝盛正!