介紹
android中網(wǎng)絡(luò)訪問的第三方庫(kù)github 地址:https://github.com/loopj/android-async-http
android-async-http主頁(yè):http://loopj.com/android-async-http/
特性
- 發(fā)送異步http請(qǐng)求,在匿名callback對(duì)象中處理response信息;
- http請(qǐng)求發(fā)生在UI(主)線程之外的異步線程中;
- 內(nèi)部采用線程池來(lái)處理并發(fā)請(qǐng)求;
- 通過(guò)RequestParams類構(gòu)造GET/POST;
- 內(nèi)置多部分文件上傳,不需要第三方庫(kù)支持;
- 流式Json上傳,不需要額外的庫(kù);
- 能處理環(huán)行和相對(duì)重定向;
- 和你的app大小相比來(lái)說(shuō),庫(kù)的size很小,所有的一切只有90kb;
- 在各種各樣的移動(dòng)連接環(huán)境中具備自動(dòng)智能請(qǐng)求重試機(jī)制;
- 自動(dòng)的gzip響應(yīng)解碼;
- 內(nèi)置多種形式的響應(yīng)解析,有原生的字節(jié)流,string,json對(duì)象,甚至可以將 response寫到文件中;
- 永久的cookie保存,內(nèi)部實(shí)現(xiàn)用的是Android的SharedPreferences;
- 通過(guò)BaseJsonHttpResponseHandler和各種json庫(kù)集成;
- 支持SAX解析器;
- 支持各種語(yǔ)言和content編碼,不僅僅是UTF-8;
Gradle 中引用
在app的buid.gradle中添加
compile 'com.loopj.android:android-async-http:1.4.9'
使用
官方建議是通過(guò)靜態(tài)類的方法來(lái)使用
twitter的例子
<pre> import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "https://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl; }}
</pre>
在client 端就可以這么用了
import org.json.*;import com.loopj.android.http.*;class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException { TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray }
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
}
});
}
傳參:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");