Android Asynchronous Http Client 中文教程
2015-07-22 22:27
621 查看
本文为译文,原文链接https://loopj.com/android-async-http/
安卓异步http客户端
概述
这是一个异步的基于回调的Androidhttp客户端,构建于Apachehttpclient库上。所有的请求都是独立于UI线程的,与此同时回调会由handler在发起请求的线程中执行。你也可以在后台线程和服务中使用它,这个库会自动识别它的运行环境。
特点
异步请求,回调处理。
不会阻塞UI线程。
使用线程池来负担并发请求。
GET/POST参数构建。
文件分部上传(不需要其它库的支持)。
流化上传JSON(不需要其它库的支持)
处理循环和相关的重定向。
包大小只有90kb
自动智能请求重试,对不稳定的移动链接而优化。
自动使用gzip响应编码,以支持超快请求。
二进制的通讯协议,使用BinaryHttpResponseHandler。
内建相应解析为JSOn的机制,使用JsonHttpResponseHandler。
直接保存相应,使用FileAsyncHttpResponseHandler。
持久的cookie存储,保存在SharedPreferences中。
集成JacksonJSON,Gson以及其它JSON系列框架,通过使用BaseJsonHttpResponseHandler。
支持SAX解析,通过使用SaxAsyncHttpResponseHandler。
支持语言和内容的编码,不仅仅是UTF-8。
使用本库的高端App和开发者
Instagram
Pinterest
FrontlineCommando(GluGames)
Heyzap
Pose
Thousandsmoreapps…
安装和基本使用
添加maven依赖使用gradle构建。
dependencies{
compile'com.loopj.android:android-async-http:1.4.8'
}
导入http包
创建一个新的AsyncHttpClient实例,并发送请求:
推荐用法:创建一个静态的http客户端
在这个例子中,我们将创建一个http客户端,使用静态的访问器,使我们与Twitter的API的通信更容易。
这样话,你后面在使用Twitter的api就很容易了:
查看AsyncHttpClient,RequestParams和AsyncHttpResponseHandler的java文档来了解更多。
持久的cookie存储,使用PersistentCookieStore
这个库也包含了一个持久的cookie存储功能,使用了apachehtpclientcookiestore接口,自动的存储cookies到sharedpreferences。
这个特别有用,当你想使用cookies来管理带你的鉴权会话,因为用户在退出或者重新打开你的app时,都可以保持登录状态。
第一步,建立一个AsyncHttpClient的实例:
使用activity的context或者application的context来构建这个客户端的cookies的PersistentCookieStore实例。
现在,任何从服务端获得的cookies将会持久的存储。
添加你自己的cookies,只要构建一个cookies然后调用addcookie。
看PersistentCookieStoreJavadoc获得更多信息。
添加GET/POST参数,使用RequestParams
你的GET或者POST请求都可以添加参数。
创建空的参数集并添加参数:
创建单参数的RequestParams:
从已有的Map中创建参数集:
看RequestParamsJavadoc了解更多。
使用参数上传文件
参数集支持分部上传文件,如下:
添加输入流到参数来上传:
添加一个对象到参数来上传:
添加一个比特数据到参数来上传:
看RequestParamsJavadoc了解更多。
下载二进制数据使用FileAsyncHttpResponseHandler
看FileAsyncHttpResponseHandlerJavadoc了解更多。
添加HTTP基本鉴权证书
一些API服务可能要求HTTP基本访问认证,因此可能需要给请求提供用户名/密码来认证。使用setBasicAuth()来提供认证。
对特定请求设置username/password对任何主机和域名,默认的,认证对任何主机域名和端口都起作用。
推荐,你也可以提供一个更详细的鉴权范围。
看RequestParamsJavadoc了解更多。
在设备上测试
你可以在真机或者模拟器上测试这个库,使用提供的例子程序。例子程序实现了所有的重要的库功能。你可以把它们当作实际代码的灵感。
例子程序:https://github.com/loopj/android-async-http/tree/master/sample
为了运行例子,从android-async-http的github库上克隆项目。并且在root下运行如下命令:
这个命令会安装例子程序在链接的机器上,所有的例子都可以快速的运行,如果不行,请在https://github.com/loopj/android-async-http/issues提交问题。
从源码构建
首先克隆项目,然后安装Androidsdk和gradle,然后执行:
将会产生目标文件:
报告bug和特性需求
https://github.com/loopj/android-async-http/issues
工作人员和贡献者
JamesSmith(https://github.com/loopj)
CreatorandMaintainer
MarekSebera(https://github.com/smarek)
Maintainersince1.4.4release
NoorDawod(https://github.com/fineswap)
Maintainersince1.4.5release
LucianoVitti(https://github.com/xAnubiSx)
CollaboratedonSampleApplication
JasonChoy(https://github.com/jjwchoy)
AddedsupportforRequestHandlefeature
MicahFivecoate(https://github.com/m5)
MajorContributor,includingtheoriginalRequestParams
TheDroidFuProject(https://github.com/kaeppler/droid-fu)
Inspirationandcodeforbetterhttpretries
RafaelSanches(https://blog.rafaelsanches.com)
OriginalSimpleMultipartEntitycode
AnthonyPersaud(https://github.com/apersaud)
AddedsupportforHTTPBasicAuthenticationrequests.
LindenDarling(https://github.com/coreform)
Addedsupportforbinary/imageresponses
许可证
ApacheLicense,Version2.0.
https://www.apache.org/licenses/LICENSE-2.0
关于作者
JamesSmith,BritishentrepreneuranddeveloperbasedinSanFrancisco.
I'mtheco-founderofBugsnagwithSimonMaynard,
andfrom2009to2012IleduptheproductteamasCTOofHeyzap.
Follow@loopj
本文下载
http://download.csdn.net/detail/zhounanzhaode/8924505
安卓异步http客户端
概述
这是一个异步的基于回调的Androidhttp客户端,构建于Apachehttpclient库上。所有的请求都是独立于UI线程的,与此同时回调会由handler在发起请求的线程中执行。你也可以在后台线程和服务中使用它,这个库会自动识别它的运行环境。
特点
异步请求,回调处理。
不会阻塞UI线程。
使用线程池来负担并发请求。
GET/POST参数构建。
文件分部上传(不需要其它库的支持)。
流化上传JSON(不需要其它库的支持)
处理循环和相关的重定向。
包大小只有90kb
自动智能请求重试,对不稳定的移动链接而优化。
自动使用gzip响应编码,以支持超快请求。
二进制的通讯协议,使用BinaryHttpResponseHandler。
内建相应解析为JSOn的机制,使用JsonHttpResponseHandler。
直接保存相应,使用FileAsyncHttpResponseHandler。
持久的cookie存储,保存在SharedPreferences中。
集成JacksonJSON,Gson以及其它JSON系列框架,通过使用BaseJsonHttpResponseHandler。
支持SAX解析,通过使用SaxAsyncHttpResponseHandler。
支持语言和内容的编码,不仅仅是UTF-8。
使用本库的高端App和开发者
安装和基本使用
添加maven依赖使用gradle构建。
dependencies{
compile'com.loopj.android:android-async-http:1.4.8'
}
导入http包
import[code]com.loopj.android.http.*;[/code]
创建一个新的AsyncHttpClient实例,并发送请求:
AsyncHttpClient[code]client=newAsyncHttpClient();
client.get("https://www.google.com",[code]newAsyncHttpResponseHandler(){
[code]
[code]@Override
[code]publicvoidonStart(){
[code]//calledbeforerequestisstarted
[code]}
[code]
[code]@Override
[code]publicvoidonSuccess(intstatusCode,Header[]headers,byte[]response){
[code]//calledwhenresponseHTTPstatusis"200OK"
[code]}
[code]
[code]@Override
[code]publicvoidonFailure(intstatusCode,Header[]headers,byte[]errorResponse,Throwablee){
[code]//calledwhenresponseHTTPstatusis"4XX"(eg.401,403,404)
[code]}
[code]
[code]@Override
[code]publicvoidonRetry(intretryNo){
[code]//calledwhenrequestisretried
[code]}
});
推荐用法:创建一个静态的http客户端
在这个例子中,我们将创建一个http客户端,使用静态的访问器,使我们与Twitter的API的通信更容易。
import[code]com.loopj.android.http.*;
[code]
public[code]classTwitterRestClient{
[code]privatestaticfinalStringBASE_URL="https://api.twitter.com/1/";
[code]
[code]privatestaticAsyncHttpClientclient=newAsyncHttpClient();
[code]
[code]publicstaticvoidget(Stringurl,RequestParamsparams,AsyncHttpResponseHandlerresponseHandler){
[code]client.get(getAbsoluteUrl(url),params,responseHandler);
[code]}
[code]
[code]publicstaticvoidpost(Stringurl,RequestParamsparams,AsyncHttpResponseHandlerresponseHandler){
[code]client.post(getAbsoluteUrl(url),params,responseHandler);
[code]}
[code]
[code]privatestaticStringgetAbsoluteUrl(StringrelativeUrl){
[code]returnBASE_URL+relativeUrl;
[code]}
}
这样话,你后面在使用Twitter的api就很容易了:
import[code]org.json.*;
import[code]com.loopj.android.http.*;
[code]
class[code]TwitterRestClientUsage{
[code]publicvoidgetPublicTimeline()throwsJSONException{
[code]TwitterRestClient.get("statuses/public_timeline.json",null,newJsonHttpResponseHandler(){
[code]@Override
[code]publicvoidonSuccess(intstatusCode,Header[]headers,JSONObjectresponse){
[code]//IftheresponseisJSONObjectinsteadofexpectedJSONArray
[code]}
[code]
[code]@Override
[code]publicvoidonSuccess(intstatusCode,Header[]headers,JSONArraytimeline){
[code]//Pulloutthefirsteventonthepublictimeline
[code]JSONObjectfirstEvent=timeline.get(0);
[code]StringtweetText=firstEvent.getString("text");
[code]
[code]//Dosomethingwiththeresponse
[code]System.out.println(tweetText);
[code]}
[code]});
[code]}
}
查看
持久的cookie存储,使用PersistentCookieStore
这个库也包含了一个持久的cookie存储功能,使用了apachehtpclientcookiestore接口,自动的存储cookies到sharedpreferences。
这个特别有用,当你想使用cookies来管理带你的鉴权会话,因为用户在退出或者重新打开你的app时,都可以保持登录状态。
第一步,建立一个AsyncHttpClient的实例:
AsyncHttpClient[code]myClient=newAsyncHttpClient();[/code]
使用activity的context或者application的context来构建这个客户端的cookies的PersistentCookieStore实例。
PersistentCookieStore[code]myCookieStore=newPersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
现在,任何从服务端获得的cookies将会持久的存储。
添加你自己的cookies,只要构建一个cookies然后调用addcookie。
BasicClientCookie[code]newCookie=newBasicClientCookie("cookiesare","awesome");
newCookie.setVersion(1);[code]
newCookie.setDomain("mydomain.com");[code]
newCookie.setPath("/");[code]
myCookieStore.addCookie(newCookie);
看
添加GET/POST参数,使用RequestParams
你的GET或者POST请求都可以添加参数。
RequestParams可以以下几种方式构建:
创建空的参数集并添加参数:
RequestParams[code]params=newRequestParams();
params.put("key",[code]"value");
params.put("more",[code]"data");[/code]
创建单参数的RequestParams:
RequestParams[code]params=newRequestParams("single","value");[/code]
从已有的Map中创建参数集:
HashMap<String,[code]String>paramMap=newHashMap<String,String>();
paramMap.put("key",[code]"value");
RequestParams[code]params=newRequestParams(paramMap);[/code]
看
使用参数上传文件
参数集支持分部上传文件,如下:
添加输入流到参数来上传:
InputStream[code]myInputStream=blah;
RequestParams[code]params=newRequestParams();
params.put("secret_passwords",[code]myInputStream,"passwords.txt");[/code]
添加一个对象到参数来上传:
File[code]myFile=newFile("/path/to/file.png");
RequestParams[code]params=newRequestParams();
try[code]{
[code]params.put("profile_picture",myFile);
}[code]catch(FileNotFoundExceptione){}[/code]
添加一个比特数据到参数来上传:
byte[][code]myByteArray=blah;
RequestParams[code]params=newRequestParams();
params.put("soundtrack",[code]newByteArrayInputStream(myByteArray),"she-wolf.mp3");[/code]
看
下载二进制数据使用FileAsyncHttpResponseHandler
FileAsyncHttpResponseHandler可以用来下载二进制数据比如图片和其它文件。例子:
AsyncHttpClient[code]client=newAsyncHttpClient();
client.get("https://example.com/file.png",[code]newFileAsyncHttpResponseHandler(/*Context*/this){
[code]@Override
[code]publicvoidonSuccess(intstatusCode,Header[]headers,Fileresponse){
[code]//Dosomethingwiththefile`response`
[code]}
});
看
添加HTTP基本鉴权证书
一些API服务可能要求HTTP基本访问认证,因此可能需要给请求提供用户名/密码来认证。使用setBasicAuth()来提供认证。
对特定请求设置username/password对任何主机和域名,默认的,认证对任何主机域名和端口都起作用。
AsyncHttpClient[code]client=newAsyncHttpClient();
client.setBasicAuth("username","password/token");[code]
client.get("https://example.com");
推荐,你也可以提供一个更详细的鉴权范围。
AsyncHttpClient[code]client=newAsyncHttpClient();
client.setBasicAuth("username","password",[code]newAuthScope("example.com",80,AuthScope.ANY_REALM));
client.get("https://example.com");
看
在设备上测试
你可以在真机或者模拟器上测试这个库,使用提供的例子程序。例子程序实现了所有的重要的库功能。你可以把它们当作实际代码的灵感。
例子程序:
为了运行例子,从android-async-http的github库上克隆项目。并且在root下运行如下命令:
[code]gradle:sample:installDebug
这个命令会安装例子程序在链接的机器上,所有的例子都可以快速的运行,如果不行,请在
从源码构建
首先克隆项目,然后安装Androidsdk和gradle,然后执行:
[code]gradle:library:jarRelease
将会产生目标文件:
{repository_root}/library/build/libs/library-1.4.8.jar.
报告bug和特性需求
工作人员和贡献者
JamesSmith(
CreatorandMaintainer
MarekSebera(
Maintainersince1.4.4release
NoorDawod(
Maintainersince1.4.5release
LucianoVitti(
CollaboratedonSampleApplication
JasonChoy(
AddedsupportforRequestHandlefeature
MicahFivecoate(
MajorContributor,includingtheoriginalRequestParams
TheDroidFuProject(
Inspirationandcodeforbetterhttpretries
RafaelSanches(
OriginalSimpleMultipartEntitycode
AnthonyPersaud(
AddedsupportforHTTPBasicAuthenticationrequests.
LindenDarling(
Addedsupportforbinary/imageresponses
许可证
ApacheLicense,Version2.0.
关于作者
JamesSmith,BritishentrepreneuranddeveloperbasedinSanFrancisco.
I'mtheco-founderof
andfrom2009to2012IleduptheproductteamasCTOof
本文下载
相关文章推荐
- 网络编程基础知识
- 【工业串口和网络软件通讯平台(SuperIO)教程】三.二次开发流程
- 【工业串口和网络软件通讯平台(SuperIO)教程】三.二次开发流程
- Https要点
- 网络基础知识--网络架构及OSI七层协议
- 无线网络安全--BackTrack 的U盘启动盘制作
- 封装http请求返回统一json格式数据的网络操作
- Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.3
- Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.2
- 无线网络安全
- Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.1
- 由ASP.NET所谓前台调用后台、后台调用前台想到HTTP——理论篇
- 如何快速查看自己电脑使用的是什么网络
- TCP/IP 三次握手、四次挥手
- Java TCP通信(服务器和客户端代码)
- 云计算和大数据时代网络技术揭秘(十三)VXLAN
- Android基础之Http基础详解
- TCP/IP学习笔记(3)--ARP和RARP协议
- 史上最全 前端开发面试问题及答案整理 http://segmentfault.com/blog/trigkit4/1190000002562454
- 【Xilinx】【Spartan6】BUFG网络上的时钟信号如何通过普通IO输出