概述
Android Asynchronous Http Client是基于异步回调的Android内置的Apache HttpClient库HTTP客户端。所有的请求都是在你的应用程序的主要用户界面之外,但任何回调逻辑都会在同一个线程上执行,因为回调是使用安卓的处理程序消息传递的。您还可以在服务或后台线程中使用它,库将自动识别上下文是哪个上下文的。
特征
1.利用版4.3.6上游HttpClient代替Android提供defaulthttpclient
2.与安卓23和更高
3.进行异步HTTP请求,处理匿名回调响应
4.HTTP请求发生在UI线程之外
5.使用线程池并发请求限制资源的使用
6.GET / POST参数生成器(requestparams)
7.部分没有额外的第三方的库文件上传
8.从JSON上传没有额外的图书馆
9.处理循环和相对重定向
10.内存消耗较小
11.自动智能请求重试点状移动连接优化
12.自动gzip响应解码速度超快的请求支持
13.与binaryhttpresponsehandler二进制协议通信
14.内置响应解析成JSON与jsonhttpresponsehandler
15.节能反应直接进入文件fileasynchttpresponsehandler
16.持久性cookie存储,保存cookie到你的应用程序的SharedPreferences
17.杰克逊JSON集成,gson或其他JSON序列化库basejsonhttpresponsehandler(DE)
18对于SAX解析器与saxasynchttpresponsehandler支持
19.语言和内容编码的支持,不仅仅是UTF-8
安装和基本使用
1.导包
2.创建一个新的asynchttpclient实例并提出要求:
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://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
}
});
3.实现静态的HTTP客户端
在这个例子中,我们将做一个静态访问HTTP客户端类可以很容易地与推特的API进行沟通。
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;
}
}
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);
}
});
}
}
4.与persistentcookiestore持久性cookie存储
这个库还包括一个persistentcookiestore是Apache HttpClient存储机制的界面,自动保存在Android设备SharedPreferences存储cookies的实现。
这是非常有用的,如果你想使用的cookie来管理认证会话,因为用户将继续登录,即使在关闭和重新打开你的应用程序.
首先,创建一个实例asynchttpclient:
AsyncHttpClient myClient = new AsyncHttpClient();
现在这个客户端的cookie存储是persistentcookiestore新实例,构造活动或应用上下文(通常这就足够了):
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
从服务器接收到的任何的饼干都将被储存在持久性的饼干存储中。
添加您自己的饼干店,简单地建立一个新的cookie和呼叫addcookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
5.增加 GET/POST请求 参数
创建空requestparams立即添加一些参数:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
创建一个单参数requestparams:
RequestParams params = new RequestParams("single", "value");
从键/值的字符串一个现有的地图创建requestparams:
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
6.用requestparams上传文件
添加一个InputStream的requestparams上传:
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
添加一个文件对象的requestparams上传:
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
添加一个字节数组的requestparams上传:
byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
7.下载的二进制数据fileasynchttpresponsehandler
在fileasynchttpresponsehandler类可以用来读取二进制数据,如图像和其他文件。例如:
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {
@Override
public void onSuccess(int statusCode, Header[] headers, File response) {
// Do something with the file `response`
}
});
8.添加HTTP基本身份验证
有些要求可能需要用户名/密码认证处理API服务,使用HTTP基本接入认证请求。你可以使用的方法setbasicauth()提供您的凭据。
为特定的请求设置用户名/密码。默认情况下,身份验证范围为任何主机、端口和域。
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password/token");
client.get("https://example.com");
您还可以提供一个更具体的认证范围(推荐)
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("https://example.com");