写在代码前的话:
基于Apache的HttpClient库构建的Android异步基于回调的Http客户端 。所有请求都是在应用的主UI线程之外进行的,但是任何回调逻辑都将在与使用Android的Handler消息传递创建的回调相同的线程上执行。
也可以在Service或后台线程中使用它,库将自动识别在哪个上下文中运行。
还想知道更多Android的基于回调的基本用法,以及各个大厂面试专题,那就:https://shimo.im/docs/xTwwvXtvYQ3HgxVx/
特征
- 使用版本4.3.6的上游HttpClient代替Android提供的DefaultHttpClient
- 与Android API 23及更高版本兼容
- 发出异步 HTTP请求,处理匿名回调中的响
- HTTP请求发生在UI线程之外
- 请求使用线程池限制并发资源的使用
- GET / POST 参数构建器(RequestParams)
- 多部分文件上传,没有其他第三方库
- 无需其他库即可流式传输JSON上传
- 处理循环和相对重定向
- 应用程序的微小开销,所有内容仅90kb
- 优化的自动智能请求重试功能,适用于不稳定的移动连接
- 自动gzip响应解码支持超快速请求
- 与二进制协议通讯
BinaryHttpResponseHandler
- 内置响应解析成JSON 与
JsonHttpResponseHandler
- 将响应直接保存到文件中
FileAsyncHttpResponseHandler
- 永久性cookie存储,将cookie保存到应用程序的SharedPreferences中
- 与Jackson JSON,Gson或其他JSON(反)序列化库集成
BaseJsonHttpResponseHandler
- 支持SAX解析器
SaxAsyncHttpResponseHandler
- 支持语言和内容编码,而不仅仅是UTF-8
安装和基本用法
使用Gradle构建脚本以格式添加Maven依赖项
dependencies {
compile 'com.loopj.android:android-async-http:1.4.9'
}
导入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客户端
在此示例中,我们将使用静态访问器创建一个http客户端类,以使其易于与Twitter的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;
}
}
然后,这使得在代码中使用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);
}
});
}
}
还可以查看我的石墨文档,获取更多详细信息,以及大厂面试真题。
永久性Cookie存储 PersistentCookieStore
该库还包括一个PersistentCookieStore
Apache HttpClient CookieStore
接口的实现,该接口自动将cookie保存到SharedPreferences
Android设备上的存储中。
如果您想使用Cookie来管理身份验证会话,这将非常有用,因为即使关闭并重新打开您的应用程序,用户仍将保持登录状态。
首先,创建的实例AsyncHttpClient
:
AsyncHttpClient myClient = new AsyncHttpClient();
现在,将此客户的Cookie存储设置为的新实例,该实例是 PersistentCookieStore
使用活动或应用程序上下文构造的(通常this
就足够了):
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
现在,从服务器收到的所有cookie都将存储在持久性cookie存储中。
要将自己的cookie添加到商店,只需构造一个新的cookie并调用addCookie
:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
使用以下命令添加GET / POST参数 RequestParams
在RequestParams
类用于可选的GET或POST参数添加到您的要求。RequestParams
可以通过多种方式构建和构造:
创建空RequestParams
并立即添加一些参数:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
RequestParams
为单个参数创建:
RequestParams params = new RequestParams("single", "value");
创建RequestParams
从现有的Map
键/值的字符串:
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
使用上传文件 RequestParams
该RequestParams
班还支持多文件上传,如下所示:
一个添加InputStream
到RequestParams
上传:
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
向添加一个File
对象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");
使用下载二进制数据 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基本访问身份验证请求的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");
在设备上测试
您可以使用提供的示例应用程序在真实设备或仿真器上测试该库。示例应用程序实现了库的所有重要功能,您可以将其用作灵感来源。
要运行示例应用程序,请克隆android-async-http github存储库并在其根目录中运行命令:
gradle :sample:installDebug
它将在连接的设备上安装示例应用程序,所有示例都可以立即运行。
从源头建造
要从.jar
源代码构建文件,请首先克隆android-async-http github存储库。然后,您必须安装Android SDK和Gradle buildscript,然后运行:
gradle :library:jarRelease
这将在path中生成一个文件{repository_root}/library/build/libs/library-1.4.9.jar
。