博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android Asynchronous Http Client 中文教程
阅读量:6856 次
发布时间:2019-06-26

本文共 6960 字,大约阅读时间需要 23 分钟。

本文为译文,原文链接https://loopj.com/android-async-http/

安卓异步httpclient

概述

这是一个异步的基于回调的Android http客户端,构建于Apache httpclient库上。全部的请求都是独立于UI线程的。与此同一时候回调会由handler在发起请求的线程中执行。你也能够在后台线程和服务中使用它,这个库会自己主动识别它的执行环境。

特点

异步请求,回调处理。

不会堵塞UI线程。

使用线程池来负担并发请求。

GET/POST參数构建。

文件分部上传(不须要其他库的支持)。

流化上传JSON(不须要其他库的支持)

处理循环和相关的重定向。

包大小仅仅有90kb

自己主动智能请求重试。对不稳定的移动链接而优化。

自己主动使用gzip响应编码,以支持超快请求。

二进制的通讯协议,使用BinaryHttpResponseHandler。

内建对应解析为JSOn的机制。使用JsonHttpResponseHandler。

直接保存对应。使用FileAsyncHttpResponseHandler。

持久的cookie存储,保存在SharedPreferences中。

集成 Jackson JSON,Gson以及其他JSON系列框架。通过使用BaseJsonHttpResponseHandler。

支持SAX解析。通过使用SaxAsyncHttpResponseHandler。

支持语言和内容的编码,不不过UTF-8。

 

使用本库的高端App和开发人员

 

 

安装和基本使用

加入maven依赖使用gradle构建。

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

推荐使用方法:创建一个静态的httpclient

在这个样例中,我们将创建一个httpclient,使用静态的訪问器。使我们与Twitter的API的通信更easy。

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就非常easy了:

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

查看,  和的java文档来了解很多其它。

 

持久的cookie存储,使用PersistentCookieStore

这个库也包括了一个持久的cookie存储功能,使用了apachehtpclient cookiestore接口。自己主动的存储cookies到sharedpreferences。

这个特别实用,当你想使用cookies来管理带你的鉴权会话。由于用户在退出或者又一次打开你的app时,都能够保持登录状态。

第一步,建立一个AsyncHttpClient的实例:

AsyncHttpClient myClient = new AsyncHttpClient();

使用activity的context或者application的context来构建这个client的cookies的PersistentCookieStore实例。

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

如今,不论什么从服务端获得的cookies将会持久的存储。

加入你自己的cookies。仅仅要构建一个cookies然后调用addcookie。

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

看 获得很多其它信息。

 

加入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中创建參数集:

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

 

看 了解很多其它。

 

使用參数上传文件

 

參数集支持分部上传文件,例如以下:

加入输入流到參数来上传:

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基本鉴权证书

一些API服务可能要求HTTP基本訪问认证,因此可能须要给请求提供username/password来认证。使用setBasicAuth()来提供认证。

对特定请求设置 username/password对不论什么主机和域名。默认的,认证对不论什么主机域名和port都起作用。

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库上克隆项目。而且在root下执行例如以下命令:

gradle :sample:installDebug

这个命令会安装样例程序在链接的机器上,全部的样例都能够高速的执行,假设不行,请在提交问题。

 

从源代码构建

首先克隆项目,然后安装Android sdk 和 gradle。然后运行:

gradle :library:jarRelease

将会产生目标文件: {repository_root}/library/build/libs/library-1.4.8.jar.

 

报告bug和特性需求

 

工作人员和贡献者

James Smith ()

Creator and Maintainer

Marek Sebera ()

Maintainer since 1.4.4 release

Noor Dawod ()

Maintainer since 1.4.5 release

Luciano Vitti ()

Collaborated on Sample Application

Jason Choy ()

Added support for RequestHandle feature

Micah Fivecoate ()

Major Contributor,including the original RequestParams

The Droid FuProject ()

Inspiration and code for better httpretries

Rafael Sanches ()

Original SimpleMultipartEntity code

Anthony Persaud ()

Added support for HTTP BasicAuthentication requests.

Linden Darling ()

Added support for binary/image responses

许可证

ApacheLicense, Version 2.0. 

 

关于作者

James Smith, Britishentrepreneur and developer based in San Francisco.

I'm the co-founder of  with , andfrom 2009 to 2012 I led up the product team as CTO of .

本文下载

 

转载地址:http://joyyl.baihongyu.com/

你可能感兴趣的文章
linux-firewalld
查看>>
exchange快速将断开的邮箱显示出来
查看>>
排查一些常见的系统故障
查看>>
ssh-copy-id使用及非默认22端口时报错
查看>>
C#结构的学习
查看>>
开源性能测试工具Curl-Loader
查看>>
Linux学习笔记(一)
查看>>
构造函数
查看>>
Android 之活动任务堆栈详解
查看>>
Redhat5.4上的nagios的安装
查看>>
用TCP和TLS为即时通讯搭建通信通道
查看>>
Linux初级脚本:一个简单的日志核查脚本
查看>>
Rundeck crontab格式
查看>>
配置ISA+ADSL自动拨号
查看>>
08-BGP FAQ汇总
查看>>
.NET 2.0中的企业库异常处理块
查看>>
Datanode 死锁
查看>>
【Unity3D 游戏开发之一】搭建Unity3D环境&导出自带Demo示例;
查看>>
有关弹窗页面的注意问题
查看>>
Linux裁剪一个MINI系统
查看>>