Android Asynchronous Http Client 中文教程
本文为译文,原文链接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 实例,并发送请求:
AsyncHttpClientclient=newAsyncHttpClient();
client.get("https://www.google.com", new AsyncHttpResponseHandler() {
@Override
publicvoidonStart(){
// called before request is started
}
@Override
publicvoidonSuccess(intstatusCode,Header[]headers,byte[]response){
// called when response HTTP status is "200 OK"
}
@Override
publicvoidonFailure(intstatusCode,Header[]headers,byte[]errorResponse,Throwablee){
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
publicvoidonRetry(intretryNo){
// called when request is retried
}
});
推荐使用方法:创建一个静态的httpclient
在这个样例中,我们将创建一个httpclient,使用静态的訪问器。使我们与Twitter的API的通信更easy。
importcom.loopj.android.http.*;
publicclassTwitterRestClient{
privatestaticfinalStringBASE_URL="https://api.twitter.com/1/";
privatestaticAsyncHttpClientclient=newAsyncHttpClient();
publicstaticvoidget(Stringurl,RequestParamsparams,AsyncHttpResponseHandlerresponseHandler){
client.get(getAbsoluteUrl(url),params,responseHandler);
}
publicstaticvoidpost(Stringurl,RequestParamsparams,AsyncHttpResponseHandlerresponseHandler){
client.post(getAbsoluteUrl(url),params,responseHandler);
}
privatestaticStringgetAbsoluteUrl(StringrelativeUrl){
returnBASE_URL+relativeUrl;
}
}
这样话,你后面在使用Twitter的api就非常easy了:
importorg.json.*;
importcom.loopj.android.http.*;
classTwitterRestClientUsage{
publicvoidgetPublicTimeline()throwsJSONException{
TwitterRestClient.get("statuses/public_timeline.json",null,newJsonHttpResponseHandler(){
@Override
publicvoidonSuccess(intstatusCode,Header[]headers,JSONObjectresponse){
// If the response is JSONObject instead of expected JSONArray
}
@Override
publicvoidonSuccess(intstatusCode,Header[]headers,JSONArraytimeline){
// Pull out the first event on the public timeline
JSONObjectfirstEvent=timeline.get(0);
StringtweetText=firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
}
});
}
}
查看AsyncHttpClient, RequestParams 和AsyncHttpResponseHandler的java文档来了解很多其它。
持久的cookie存储,使用PersistentCookieStore
这个库也包括了一个持久的cookie存储功能,使用了apachehtpclient cookiestore接口。自己主动的存储cookies到sharedpreferences。
这个特别实用,当你想使用cookies来管理带你的鉴权会话。由于用户在退出或者又一次打开你的app时,都能够保持登录状态。
第一步,建立一个AsyncHttpClient的实例:
AsyncHttpClientmyClient=newAsyncHttpClient();
使用activity的context或者application的context来构建这个client的cookies的PersistentCookieStore实例。
PersistentCookieStoremyCookieStore=newPersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
如今,不论什么从服务端获得的cookies将会持久的存储。
加入你自己的cookies。仅仅要构建一个cookies然后调用addcookie。
BasicClientCookienewCookie=newBasicClientCookie("cookiesare","awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
看PersistentCookieStoreJavadoc 获得很多其它信息。
加入GET/POST參数,使用RequestParams
你的GET或者POST请求都能够加入參数。
RequestParams 能够下面几种方式构建:
创建空的參数集并加入參数:
RequestParamsparams=newRequestParams();
params.put("key", "value");
params.put("more", "data");
创建单參数的RequestParams :
RequestParamsparams=newRequestParams("single","value");
从已有的Map中创建參数集:
HashMap<String,String>paramMap=newHashMap<String,String>();
paramMap.put("key", "value");
RequestParamsparams=newRequestParams(paramMap);
看RequestParamsJavadoc 了解很多其它。
使用參数上传文件
參数集支持分部上传文件,例如以下:
加入输入流到參数来上传:
InputStreammyInputStream=blah;
RequestParamsparams=newRequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
加入一个对象到參数来上传:
FilemyFile=newFile("/path/to/file.png");
RequestParamsparams=newRequestParams();
try{
params.put("profile_picture",myFile);
}catch(FileNotFoundExceptione){}
加入一个比特数据到參数来上传:
byte[]myByteArray=blah;
RequestParamsparams=newRequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
看RequestParamsJavadoc 了解很多其它。
下载二进制数据使用FileAsyncHttpResponseHandler
FileAsyncHttpResponseHandler 能够用来下载二进制数据比方图片和其他文件。样例:
AsyncHttpClientclient=newAsyncHttpClient();
client.get("https://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {
@Override
publicvoidonSuccess(intstatusCode,Header[]headers,Fileresponse){
// Do something with the file `response`
}
});
看FileAsyncHttpResponseHandlerJavadoc 了解很多其它。
加入HTTP基本鉴权证书
一些API服务可能要求HTTP基本訪问认证,因此可能须要给请求提供username/password来认证。使用setBasicAuth()来提供认证。
对特定请求设置 username/password对不论什么主机和域名。默认的,认证对不论什么主机域名和port都起作用。
AsyncHttpClientclient=newAsyncHttpClient();
client.setBasicAuth("username","password/token");
client.get("https://example.com");
推荐,你也能够提供一个更具体的鉴权范围。
AsyncHttpClientclient=newAsyncHttpClient();
client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("https://example.com");
看 RequestParams Javadoc 了解很多其它。
在设备上測试
你能够在真机或者模拟器上測试这个库。使用提供的样例程序。样例程序实现了全部的重要的库功能。
你能够把它们当作实际代码的灵感。
样例程序:https://github.com/loopj/android-async-http/tree/master/sample
为了执行样例,从android-async-http的github库上克隆项目。而且在root下执行例如以下命令:
gradle :sample:installDebug
这个命令会安装样例程序在链接的机器上,全部的样例都能够高速的执行,假设不行,请在https://github.com/loopj/android-async-http/issues提交问题。
从源代码构建
首先克隆项目,然后安装Android sdk 和 gradle。然后运行:
gradle :library:jarRelease
将会产生目标文件: {repository_root}/library/build/libs/library-1.4.8.jar.
报告bug和特性需求
https://github.com/loopj/android-async-http/issues
工作人员和贡献者
James Smith (https://github.com/loopj)
Creator and Maintainer
Marek Sebera (https://github.com/smarek)
Maintainer since 1.4.4 release
Noor Dawod (https://github.com/fineswap)
Maintainer since 1.4.5 release
Luciano Vitti (https://github.com/xAnubiSx)
Collaborated on Sample Application
Jason Choy (https://github.com/jjwchoy)
Added support for RequestHandle feature
Micah Fivecoate (https://github.com/m5)
Major Contributor,including the original RequestParams
The Droid FuProject (https://github.com/kaeppler/droid-fu)
Inspiration and code for better httpretries
Rafael Sanches (https://blog.rafaelsanches.com)
Original SimpleMultipartEntity code
Anthony Persaud (https://github.com/apersaud)
Added support for HTTP BasicAuthentication requests.
Linden Darling (https://github.com/coreform)
Added support for binary/image responses
许可证
ApacheLicense, Version 2.0.
https://www.apache.org/licenses/LICENSE-2.0
关于作者
James Smith, Britishentrepreneur and developer based in San Francisco.
I'm the co-founder of Bugsnag with Simon Maynard,
andfrom 2009 to 2012 I led up the product team as CTO of Heyzap.
本文下载
http://download.csdn.net/detail/zhounanzhaode/8924505
Android Asynchronous Http Client 中文教程的更多相关文章
- Android Asynchronous Http Client
Features Make asynchronous HTTP requests, handle responses in anonymous callbacks HTTP requests happ ...
- 【转】Android Studio-1.2版本设置教程
如果重新安装Android Studio的话要重新配置风格选项啥的,这篇是个很好的教程,原文链接:http://blog.csdn.net/skykingf/article/details/45485 ...
- Android Studio下载及使用教程(转载)
(一)下载及相关问题解决: Android Studio 下载地址,目前最新可下载地址,尽量使用下载工具. Android Studio正式发布,给Android开发者带来了不小的惊喜.但是下载地址却 ...
- Android自动化压力测试图解教程——Monkey工具
[置顶] Android自动化压力测试图解教程--Monkey工具 标签: 测试androidprofiling工具测试工具文档 2012-04-01 10:16 38185人阅读 评论(10) 收藏 ...
- PuTTY 中文教程
PuTTY 中文教程 更新记录 2006-11-29初步完成想写的这些东西 2007-06-11PuTTY 的最新版本到了0.6:修改了一下 SSH 隧道:添加了 SSH 反向隧道:添加了用 SSH ...
- Netty4.x中文教程系列(二) Hello World !
在中国程序界.我们都是学着Hello World !慢慢成长起来的.逐渐从一无所知到熟悉精通的. 第二章就从Hello World 开始讲述Netty的中文教程. 首先创建一个Java项目.引入一个N ...
- Netty4.x中文教程系列(四) 对象传输
Netty4.x中文教程系列(四) 对象传输 我们在使用netty的过程中肯定会遇到传输对象的情况,Netty4通过ObjectEncoder和ObjectDecoder来支持. 首先我们定义一个U ...
- 【转】Android Studio安装配置学习教程指南 下载和安装--不错
背景 相信大家对Android Studio已经不陌生了,Android Studio是Google于2013 I/O大会针对Android开发推出的新的开发工具,目前很多开源项目都已经在采用,Goo ...
- CEF中文教程(google chrome浏览器控件) -- Windows下编译Chromium
CEF中文教程(google chrome浏览器控件) -- CEF简介 2013-04-10 16:48 42928人阅读 评论(4) 收藏 举报 分类: CEF(2) 目录(?)[+] ...
随机推荐
- 【IDEA】使用intellij的idea集成开发工具中的git插件
注意:这里并没有介绍git客户端的安装,如果要安装客户端,大家可以参考如下的链接: http://www.runoob.com/git/git-install-setup.html 1.在使用这个id ...
- android 研究的环境搭建、高效工具、网站资源
================= 2015 年 10 月 14 号 更新 著名的android开源社区xda有一个帖子,详细描述了android开发和研究环境的初始搭建过程: http://for ...
- Linux驱动修炼之道-SPI驱动框架源码分析(上)【转】
转自:http://blog.csdn.net/lanmanck/article/details/6895318 SPI驱动架构,以前用过,不过没这个详细,跟各位一起分享: 来自:http://blo ...
- 有关BOM(Browser Object Model)的内容
包括: BOM概述 BOM模型 Window对象(常用属性和方法,窗口的打开,窗口的关闭,模态对话框,定时器) Navigator对象(遍历navigator对象的所有属性,Navigator 对象集 ...
- android的百度地图开发(二) 定位
参考:http://blog.csdn.net/mr_wzc/article/details/51590485 第一步,初始化LocationClient类 //获取地图控件引用 mMapView = ...
- Delphi 给结构体指针分配内存,用new(p),释放用dispose(p)
来自:http://blog.163.com/zhangzhifeng688%40126/blog/static/1652627582010102261748481/ 给结构体指针分配内存 但在很多 ...
- MSSQL—列记录合并成一行
在项目开发中,有时会碰到将列记录合并为一行的情况,例如根据地区将人员姓名合并,或根据拼音首字母合并城市等,下面就以根据地区将人员姓名合并为例,详细讲一下合并的方法. 首先,先建一个表,并添加一些数据, ...
- (10)ERStudio
1.外键 https://jingyan.baidu.com/article/f79b7cb37e9d219144023ea6.html 第一个图标:Identifying Relationship ...
- Codeforces Round #447 (Div. 2) C. Marco and GCD Sequence【构造/GCD】
C. Marco and GCD Sequence time limit per test 1 second memory limit per test 256 megabytes input sta ...
- 【译】PHP之道(PHP the right way)
刚入门的同学觉得自己能用PHP写出各种程序就很NB了,但其实作为一个专业程序员,你得有个全面点的知识结构.单元测试总得听过,文档工具总得用用,Xss总得会防.推荐大家把<PHP the righ ...