代码干货|适用于Android的基于回调的Http客户端库

介绍了一个基于Apache HttpClient库构建的Android异步HTTP客户端,适用于API23及以上版本,支持异步HTTP请求、多部分文件上传、JSON上传流式传输等功能,并提供了持久性Cookie存储和自动重试机制。

写在代码前的话:

基于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客户端类,以使其易于与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);
            }
        });
    }
}

还可以查看我的石墨文档,获取更多详细信息,以及大厂面试真题。

 

该库还包括一个PersistentCookieStoreApache HttpClient CookieStore接口的实现,该接口自动将cookie保存到SharedPreferencesAndroid设备上的存储中。

如果您想使用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班还支持多文件上传,如下所示:

一个添加InputStreamRequestParams上传:

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

 

Asynchronous Http Client for Android Build Status An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries. Changelog See what is new in version 1.4.9 released on 19th September 2015 https://github.com/loopj/android-async-http/blob/1.4.9/CHANGELOG.md Javadoc Latest Javadoc for 1.4.9 release are available here (also included in Maven repository): https://loopj.com/android-async-http/doc/ Features Make asynchronous HTTP requests, handle responses in anonymous callbacks HTTP requests happen outside the UI thread Requests use a threadpool to cap concurrent resource usage GET/POST params builder (RequestParams) Multipart file uploads with no additional third party libraries Tiny size overhead to your application, only 60kb for everything Automatic smart request retries optimized for spotty mobile connections Automatic gzip response decoding support for super-fast requests Optional built-in response parsing into JSON (JsonHttpResponseHandler) Optional persistent cookie store, saves cookies into your app's SharedPreferences Examples For inspiration and testing on device we've provided Sample Application. See individual samples here on Github To run Sample application, simply clone the repository and run this command, to install it on connected device gradle :sample:installDebug Maven You can now integrate this library in your project via Maven. There are available two kind of builds. releases, maven central https://repo1.maven.org/maven2/com/loopj/android/android-async-http/ Maven URL: https://repo1.maven.org/maven2/ GroupId: com.loopj.android ArtifactId: android-async-http Version: 1.4.9 Packaging: JAR or AAR Gradle repositories { maven { mavenCentral() } } dependencies { compile 'com.loopj.android:android-async-http:1.4.9' } development snapshots https://oss.sonatype.org/content/repositories/snapshots/com/loopj/android/android-async-http/ Maven URL: https://oss.sonatype.org/content/repositories/snapshots/ GroupId: com.loopj.android ArtifactId: android-async-http Version: 1.5.0-SNAPSHOT Packaging: JAR or AAR Gradle repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } dependencies { compile 'com.loopj.android:android-async-http:1.5.0-SNAPSHOT' } Documentation, Features and Examples Full details and documentation can be found on the project page here: https://loopj.com/android-async-http/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值