整理Android Asynchronous Http Client的使用
Android Asynchronous Http Client(AHC)
一个回调式的Android网络请求库
概括:
AHC是基于Apache的HttpClient 库,所有的网络请求过程在UI线程之外进行,而回调是在Handler里面处理。也可以再Service或者后台程序里面使用,这个库会自动识别并在相应的Context进行处理。
特点:
- 异步发送HTTP请求,在回调函数中处理响应
- HTTP请求过程不在UI线程进行
- 使用线程池来管理并发数
- 支持GET/POST请求参数单独设置
- 无需其他库上传序列化JSON数据
- 处理重定向
- 体积小,只有90K
- 针对不同的网络连接对重试次数进行智能优化
- 支持gzip
- 二进制通信协议使用BinaryHttpResponseHandler处理
- 内置Json解析,使用JsonHttpResponseHandler对响应进行处理
- 使用FileAsyncHttpResponseHandler直接将响应保存到文件中
- 动态保存Cookie,将Cookie保存到应用的SharedPreferences中
- 使用BaseJsonHttpResponseHandler可以搭配Jackson JSON,Gson或者其他的Json反序列化库
- 支持SAX解析,使用SaxAsyncHttpResponseHandler
- 支持多语言多种编码方式,不只是UTF-8
谁在用
Instagram,Pinterest,Pose。。。。
怎么用
MVN:
<dependency>
<groupId>com.loopj.android</groupId>
<artifactId>android-async-http</artifactId>
<version>1.4.5</version>
</dependency>
导包:
import com.loopj.android.http.*;
创建一个AsyncHttpClient 对象并发送一个请求:
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
推荐用法:定义一个静态的Http Client
新建一个网络工具类,定义一个全局静态的Http Client。
import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "http://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;
}
}
就很容易的在需要请求网路的地方发送 网络请求:
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);
}
});
}
}
API文档 http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html
使用PersistentCookieStore保存Cookie
这个库包含一个
PersistentCookieStore
,这个类是Apache HttpClient CookieStore 接口的实现,它可以自动将cookies保存到SharedPreferences 。 如果你需要使用cookie保持认证会话,这将是特别重要的,因为即使用户关掉了应用仍然可以登录状态。 首先,创建一个AsyncHttpClient对象:
AsyncHttpClient myClient = new AsyncHttpClient();
现在将client的Cookie保存到一个PersistentCookieStore,构造方法需要有一个上下文(Activity,Application都可以,通常this就OK了)。
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
所有从server获取到的数据都持续的保存。 如果想自己设定cookie,只需要创建一个新的cookie,并调用addCookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
详情请看 PersistentCookieStore Javadoc
使用RequestParams来添加GET/POST请求参数
类RequestParams 用来为请求添加请求参数,RequestParams 可以有好几种方法进行创建和设置。 1.创建一个空的RequestParams 然后添加参数:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
2.创建一个带有一对参数的RequestParams
RequestParams params = new RequestParams("single", "value");
3.创建一个带有Map的 RequestParams
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
详情请参考: RequestParams Javadoc
使用RequestParams上传文件
RequestParams 可以支持多媒体文件上传,可以通过以下方式实现: 1.将一个Inputstream添加到将要上传的RequestParams
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
2.File方式
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
3.byte数组形式
byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
详情: RequestParams Javadoc
使用FileAsyncHttpResponseHandler下载二进制文件
类FileAsyncHttpResponseHandler 可以用来获取二进制文件,如图片,语音等文件:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, File response) {
// Do something with the file `response`
}
});
详情: FileAsyncHttpResponseHandler Javadoc
添加基本的认证凭证
一些请求可能需要类似username/password 的凭证
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password/token");
client.get("http://example.com");
当然你也可以定制
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("http://example.com");
详情: RequestParams Javadoc
说明文档: http://loopj.com/android-async-http/ GITHUB地址: https://github.com/loopj/android-async-http MVN地址: http://central.maven.org/maven2/com/loopj/android/android-async-http/