網路請求框架AsyncHttpclient的簡單使用
之所以使用asynchttpclient呢,我個人認為
一:是因為它很小100K左右。
二:它非常簡單,使用非常容易上手。
- 簡要
在介紹使用之前先來看看本框架的特性吧。
Async的網址點這裡
主要說的就是呢:
替代了android自帶提供的httpclient,支援Api23及以上,非同步請求,請求是在UIThread之外,請求是使用執行緒池去請求的,可以上傳和下載檔案,儲存cookies等。
引入庫,在android studio裡新增
dependencies {
compile 'com.loopj.android:android-async-http:1.4.9'
}
2.請求
每個應用必用的,那就是請求了,再更具需求也可能會用到上傳和下載檔案。所以今天我學習的這幾個。
1:請求:1)Get:
AsyncHttpClient asyncHttpClient = new SyncHttpClient();
asyncHttpClient.get(BASE_URL, AsyncHttpClientRespenseHandler);
這樣就完成了Get請求,BASE_URL是地址,AsyncHttpClientRespenseHandler是請求回撥。
比如
new AsyncHttpClientRespenseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//請求成功
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//請求失敗
}
}
2)Post:
asyncHttpClient.post(BASE_URL, AsyncHttpClientRespenseHandler);
或者
asyncHttpClient.post(BASE_URL, RequestParams, AsyncHttpClientRespenseHandler);
RequestParams是我們寫進去的引數。
RequestParams的用法有必要先說一下:
RequestParams requestParams=new RequestParams();
requestParams.put("key", what);
這裡是以鍵值對的方式存進去的。
好了,現在寫出了帶引數和不帶引數的post,get也可以有帶引數的
獲取一般的資料就這樣,有沒有覺得很簡單呢?當然在應用裡,自己用這樣是不夠的,我們需要自己封裝一下。
3.自我封裝
咱們先封裝一個請求類(可以用來放所有請求方法):
import android.content.Context;
import android.os.Looper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
public class nHttpClient {
private static String BASE_URL = "www.google.com";
private static AsyncHttpClient asyncHttpClient = new SyncHttpClient();
private static AsyncHttpClient syncHttpClient = new AsyncHttpClient();
/**
* post請求帶引數
* @param myHttpClientRespenseHandler
*/
private static void post(RequestParams requestParams, MyHttpClientRespenseHandler myHttpClientRespenseHandler) {
getClient().setTimeout(20000);
getClient().post(BASE_URL, requestParams, myHttpClientRespenseHandler);
}
/**
* post請求不帶引數
* @param myHttpClientRespenseHandler
*/
private static void post(MyHttpClientRespenseHandler myHttpClientRespenseHandler) {
syncHttpClient.setTimeout(20000);
syncHttpClient.post(BASE_URL, myHttpClientRespenseHandler);
}
/**
* get請求
* @param myHttpClientRespenseHandler
*/
private static void get( MyHttpClientRespenseHandler myHttpClientRespenseHandler) {
getClient().setTimeout(20000);
getClient().get(BASE_URL, myHttpClientRespenseHandler);
}
/**
*
* @return
*/
private static AsyncHttpClient getClient() {
if (Looper.myLooper() == null) {
return syncHttpClient;
} else {
return asyncHttpClient;
}
}
/**
* 取消請求(根據context)
*/
public static void cancelRequest(Context context) {
getClient().cancelRequests(context, true);
}
/**
* 獲取資料
*/
public static void getAll(String what ,MyHttpClientRespenseHandler myHttpClientRespenseHandler ) {
RequestParams requestParams=new RequestParams();
requestParams.put("key", what);
post(myHttpClientRespenseHandler);
}
/**
* 下載檔案方式1
*
* @param url
*/
public static void downloadFile(Context context, String url,
BinaryHttpResponseHandler response) {
getClient().get(context, url, response);
}
/**
* 下載檔案方式2
*
* @param url
*/
public static void downLoadFile2(Context context,String url,FileAsyncHttpResponseHandler fileAsyncHttpResponseHandler) {
getClient().get(context, url, fileAsyncHttpResponseHandler);
}
}
上傳的操作,官網的描述也很清晰了,其實就是把檔案封裝到RequestParams裡去,再進行請求。三種方式,1:接受inputStream的,第三個引數指定檔名。2:接受File的,直接put進去。3:接受byte[]型別,第三個引數制定檔名。
自己建的這個請求類的前面幾個就是請求方式方法和取消請求的方法,我們請求的時候帶上Activity型別的Context,這樣有利於請求的取消,比如在onDestry裡面我們需要取消當前頁面還未完成的請求。
接下來我們要封裝的就是RespenseHandler類了,先介紹一下它:
1.AsyncHttpResponseHandler
接收請求結果,一般重寫onSuccess及onFailure接收請求成功或失敗的訊息,還有onStart,onFinish等訊息
2.TextHttpResponseHandler
繼承自AsyncHttpResponseHandler,只是重寫了AsyncHttpResponseHandler的onSuccess和onFailure方法,將請求結果由byte陣列轉換為String
3.JsonHttpResponseHandler
也是繼承自TextHttpResponseHandler,同樣是重寫onSuccess和onFailure方法,將請求結果由String轉換為JSONObject或JSONArray
4.BaseJsonHttpResponseHandler
也是繼承自TextHttpResponseHandler,是一個泛型類,提供了parseResponse方法,子類需要提供實現,將請求結果解析成需要的型別,子類可以靈活地使用解析方法,可以直接原始解析,使用gson等。
好了,相比大家也知道了這幾個的用法了,我瞭解這個的時候最先了解的是AsyncHttpResponseHandler,但是在實際使用當中一般用的TextHttpResponseHandler。直接上程式碼:
import android.app.Activity;
import android.util.Log;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class MyHttpClientRespenseHandler extends TextHttpResponseHandler {
private String TAG = "respensehandler";
private Activity context;
public MyHttpClientRespenseHandler(Activity context) {
this.context = context;
}
@Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, String s) {
Log.i(TAG, "請求成功");
try {
JSONObject jsonObject = new JSONObject(s);
success(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, String s, Throwable throwable) {
Log.i(TAG, "請求失敗");
faile();
}
public abstract void success(JSONObject json);
public abstract void faile();
}
這樣就把RespenseHandler給封裝好了,相當於是以後請求的時候用我自己這個Handler去做回調了就更好了不是嗎?得到結果在這裡自行轉換為了json。使用的時候,我就直接得到json了。
看下使用的程式碼:
//請求json資料
nHttpClient.getAll(MyApplication.Key, new MyHttpClientRespenseHandler(getActivity()) {
@Override
public void success(JSONObject json) {
Toast.makeText(getActivity(), json.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void faile() {
Toast.makeText(getActivity(), "請求失敗", Toast.LENGTH_SHORT).show();
}
});
//下載檔案1
String[] allowedTypes = new String[]{".*"}; nHttpClient.downloadFile(getActivity(), "https://example.com/file.png", new BinaryHttpResponseHandler(allowedTypes) {
@Override
public void onStart() {
super.onStart();
//這裡執行下載開始程序的dialog
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
//下載完成操作
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
//下載過程(可以設定progressbar)
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
//下載失敗
}
});
//下載檔案2 nHttpClient.downLoadFile2(getActivity(), "https://example.com/file.png", new FileAsyncHttpResponseHandler(getActivity()) {
@Override
public void onStart() {
super.onStart();
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, File file) {
}
});
好了,講到這裡。