您的位置:首页 > 理论基础 > 计算机网络

android-async-http使用

2015-08-20 15:10 633 查看
源码:https://github.com/loopj/android-async-http

简单应用实例:https://github.com/loopj/android-async-http/tree/master/sample

提交bug或建议: https://github.com/loopj/android-async-http/issues
Android Asynchronous Http Client官方介绍:http://loopj.com/android-async-http/

总览

Android Asynchronous Http Client是在Apache HttpClient基础上基于回调的Android http客户端类库。所有的请求都不会在你app的UI主线程上执行,但是任何回调逻辑将会通过Android的Handler消息传送机制使之运行在回调类被创建的线程上。你可以在Service或后台线程上使用它,它将会自动识别运行的上下文环境。

* 回调类是用来传递给Client处理请求返回的结果

功能特性

异步执行HTTP请求,在匿名callbacks中处理响应

HTTP请求在UI主线程外执行

请求使用线程池来限制并发资源的使用情况

GET/POST参数构建者(RequestParams)

没有额外第三方库的文件分割上传

没有额外第三方库的JSON上传

处理循环和相关重定向

只占用你应用空间很小部分,仅仅90kb就可以做一切事情

为质量不一的android移动设备连接网络所设计的自动的智能的请求重发机制

自动解码响应的gzip,支持极速请求

可以与二进制通信的BinaryHttpResponseHandler

内置的可以将响应结果解析成JSON的JsonHttpResponseHandler

直接将结果保存成文件形式的FileAsyncHttpResponseHandler

持久化Cookie,保存Cookie在你app的SharedPreferences

通过BaseJsonHttpResponseHandler集成了Jackson JSON,Gson或者其他(反)序列化的JSON库

SaxAsyncHttpResponseHandler支持SAX解析器

支持语言和内容编码,而不仅仅是UTF-8

安装和基本使用

使用gradle脚本语言添加maven依赖

dependencies {
compile 'com.loopj.android:android-async-http:1.4.8'
}


导入http包

import com.loopj.android.http.*;


创建一个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
}
});


推荐用法:使用一个静态的Http Client

在下面的这个例子中,为了使访问Twitter的API变得简单,我们将使用一个静态的http client类:

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;
}
}


这样之后使得在你代码中与Twitter API协同工作变得更为简单

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);
}
});
}
}


更多详情可以查阅Javadocs里的AsyncHttpClient, RequestParams and AsyncHttpResponseHandler

使用PersistentCookieStore持久化Cookie

这个库也包含了一个继承自Apache HttpClient CookieStore接口的PersistentCookieStore ,其中Apache HttpClient的 CookieStore可以自动保存cookies 到Android设备上的SharedPreferences 。

由于用户在关闭和重新打开app后,仍然登录着,如果你想用cookies来管理会话认证,这将非常好用。

首先创建一个AsyncHttpClient实例:

AsyncHttpClient myClient = new AsyncHttpClient();


现在将此客户端的cookie实例成一个PersistentCookieStore对象:

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);


任何接收自服务端的cookies都将被存储于这里。

要添加你自己的cookies到本地存储里,只需要创建一个cookie对象并且调用addCookie即可:

BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);


使用RequestParams添加GET/POST参数

RequestParams用于添加GET 或者POST 请求参数,其创建方式有多种:

创建一个空的RequestParams 并添加参数:

RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");


创建只有单个参数的RequestParams :

RequestParams params = new RequestParams("single", "value");


使用已经存在的Map 创建RequestParams :

HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);


使用RequestParams上传文件

此外,RequestParams支持多附件上传:

上传输入流InputStream:

InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");


上传文件:

File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}


上传字节数组:

byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");


使用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`
}
});


添加HTTP 基本的授权证书

当处理HTTP基本访问认证(HTTP Basic Access Authentication)请求的API服务,一些请求也许需要用户名密码认证,你可以使用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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  async-http