官網:https://github.com/loopj/android-async-http
1.簡介
Android中網絡請求一般使用Apache HTTP Client或者採用HttpURLConnect,但是直接使用這兩個類庫需要寫大量的代碼才能完成網絡post和get請求,而使用android-async-http這個庫可以大大的簡化操作,它是基於Apache’s HttpClient ,所有的請求都是獨立在UI主線程之外,通過回調方法處理請求結果,採用android Handler message 機制傳遞信息。2.特性
(1)採用異步http請求,並通過匿名內部類處理回調結果
(2)http請求獨立在UI主線程之外
(3)採用線程池來處理併發請求
(4)採用RequestParams類創建GET/POST參數
(5)不需要第三方包即可支持Multipart file文件上傳
(6)大小隻有25kb
(7)自動爲各種移動電話處理連接斷開時請求重連
(8)超快的自動gzip響應解碼支持
(9)使用BinaryHttpResponseHandler類下載二進制文件(如圖片)
(10) 使用JsonHttpResponseHandler類可以自動將響應結果解析爲json格式
(11)持久化cookie存儲,可以將cookie保存到你的應用程序的SharedPreferences中
3.使用方法(參考官方例舉的一個訪問Twitter的API的例子,地址:http://loopj.com/android-async-http/)
LoopjRequestClient類
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
/**
* @author 付亮
*
*/
public class LoopjRequestClient {
private static final String BASE_URL = "http://xxxxxxx/";
/**
* 定義一個異步網絡客戶端 ,默認超時20秒, 當超過,默認重連次數爲5次 默認最大連接數爲10個
*/
private static AsyncHttpClient mClient = new AsyncHttpClient();
static {
mClient.setTimeout(20000);
}
/**
* 執行HTTP get請求,帶參數
*
* @param url
* 請求url相對地址
* @param params
* 請求參數
* @param responseHandler
* 數據加載句柄對象
*/
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
mClient.get(getAbsoluteUrl(url), params, responseHandler);
}
/**
* 執行HTTP get請求,不帶參數
*
* @param url
* 請求url相對地址
*
* @param responseHandler
* 數據加載句柄對象
*/
public static void get(String url, AsyncHttpResponseHandler responseHandler) {
mClient.get(getAbsoluteUrl(url), responseHandler);
}
/**
* 執行HTTP post請求,帶參數
*
* @param url
* 請求url相對地址
* @param params
* 請求參數
* @param responseHandler
* 數據加載句柄對象
*/
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
mClient.post(getAbsoluteUrl(url), params, responseHandler);
}
/**
* 執行HTTP post請求,不帶參數
*
* @param url
* 請求url相對地址
* @param responseHandler
* 數據加載句柄對象
*/
public static void post(String url, AsyncHttpResponseHandler responseHandler) {
mClient.post(getAbsoluteUrl(url), responseHandler);
}
/**
* 執行HTTP put請求,帶參數
*
* @param url
* 請求url相對地址
* @param params
* 請求參數
* @param responseHandler
* 數據加載句柄對象
*/
public static void put(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
mClient.put(getAbsoluteUrl(url), params, responseHandler);
}
/**
* 執行HTTP put請求,不帶參數
*
* @param url
* 請求url相對地址
* @param responseHandler
* 數據加載句柄對象
*/
public static void put(String url, AsyncHttpResponseHandler responseHandler) {
mClient.put(getAbsoluteUrl(url), responseHandler);
}
/**
* 將請求的url相對地址,拼接爲完整的url地址
*
* @param relativeUrl
* 請求url相對地址
* @return 完整的請求url地址
*/
private static String getAbsoluteUrl(String relativeUrl) {
String s = BASE_URL + relativeUrl;
System.out.println(s);
return s;
}
}
5. AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler三個類使用方法
(1)AsyncHttpClient
public class AsyncHttpClient extends java.lang.Object
該類通常用在android應用程序中創建異步GET, POST, PUT和DELETE HTTP請求,請求參數通過RequestParams實例創建,響應通過重寫匿名內部類 ResponseHandlerInterface的方法處理。
例子:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new ResponseHandlerInterface() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
(2)RequestParamspublic class RequestParams extends java.lang.Object
用於創建AsyncHttpClient實例中的請求參數(包括字符串或者文件)的集合
例子:
RequestParams params = new RequestParams();
params.put("username", "james");
params.put("password", "123456");
params.put("email", "[email protected]");
params.put("profile_picture", new File("pic.jpg")); // Upload a File
params.put("profile_picture2", someInputStream); // Upload an InputStream
params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
Map<String, String> map = new HashMap<String, String>();
map.put("first_name", "James");
map.put("last_name", "Smith");
params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith"
Set<String> set = new HashSet<String>(); // unordered collection
set.add("music");
set.add("art");
params.put("like", set); // url params: "like=music&like=art"
List<String> list = new ArrayList<String>(); // Ordered collection
list.add("Java");
list.add("C");
params.put("languages", list); // url params: "languages[]=Java&languages[]=C"
String[] colors = { "blue", "yellow" }; // Ordered collection
params.put("colors", colors); // url params: "colors[]=blue&colors[]=yellow"
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> user1 = new HashMap<String, String>();
user1.put("age", "30");
user1.put("gender", "male");
Map<String, String> user2 = new HashMap<String, String>();
user2.put("age", "25");
user2.put("gender", "female");
listOfMaps.add(user1);
listOfMaps.add(user2);
params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://myendpoint.com", params, responseHandler);
(3)public class AsyncHttpResponseHandler extends java.lang.Object implements ResponseHandlerInterface用於攔截和處理由AsyncHttpClient創建的請求。在匿名類AsyncHttpResponseHandler中的重寫 onSuccess(int, org.apache.http.Header[], byte[])方法用於處理響應成功的請求。此外,你也可以重寫 onFailure(int, org.apache.http.Header[], byte[], Throwable), onStart(), onFinish(), onRetry() 和onProgress(int, int)方法
例子:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// Initiated the request
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// Successfully got a response
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
{
// Response failed :(
}
@Override
public void onRetry() {
// Request was retried
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
// Progress notification
}
@Override
public void onFinish() {
// Completed the request (either success or failure)
}
});
6.利用PersistentCookieStore持久化存儲cookie
PersistentCookieStore類用於實現Apache HttpClient的CookieStore接口,可以自動的將cookie保存到Android設備的SharedPreferences中,如果你打算使用cookie來管理驗證會話,這個非常有用,因爲用戶可以保持登錄狀態,不管關閉還是重新打開你的app
(1)首先創建 AsyncHttpClient實例對象
AsyncHttpClient myClient = new AsyncHttpClient();
(2)將客戶端的cookie保存到PersistentCookieStore實例對象,帶有activity或者應用程序context的構造方法PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
(3)任何從服務器端獲取的cookie都會持久化存儲到myCookieStore中,添加一個cookie到存儲中,只需要構造一個新的cookie對象,並且調用addCookie方法BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
7.利用RequestParams上傳文件
類RequestParams支持multipart file 文件上傳
(1)在RequestParams 對象中添加InputStream用於上傳
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
(2)添加文件對象用於上傳File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
(3)添加字節數組用於上傳byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
8.用BinaryHttpResponseHandler下載二進制數據
BinaryHttpResponseHandler用於獲取二進制數據如圖片和其他文件
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) {
@Override
public void onSuccess(byte[] fileData) {
// Do something with the file
}
});
參考資料:http://loopj.com/android-async-http/
http://blog.csdn.net/hil2000/article/details/13949513
http://blog.csdn.net/mobilexu/article/details/9350467
http://blog.csdn.net/mobilexu/article/details/16114505