简介
基于Apache的HttpClient 的一个android异步包.
回调逻辑执行的线程 == 创建Callback的线程(不是创建Httpclient的线程)
举例:
new Thread(new Runnable() { @Override public void run() { Log.d(LOG_TAG, "Before Request"); client.get(Activity.this, URL, headers, null, responseHandler); Log.d(LOG_TAG, "After Request"); } }).start(); //在callback的时候,就要用runOnUiThread
特点:
1.异步请求,匿名回调处理响应
2.http请求在UI线程之外
3.请求试用线程池,共用资源
4.GET/POST 参数构建(RequestParams)
5.多文件上传,并且不需要多余3方库
6.JSON流上传
7.处理循环和定向跳转
8.包只有90k
9.自动重连,根据不同的网络连接方式
10.2进制通讯协议BinaryHttpResponseHandler
11.内置JSON解析JsonHttpResponseHandler
12.文件保存FileAsyncHttpResponseHandler
13。持续cookie存储,保存在SharedPreferences里
14支持多个Json解析,包括GSON,使用BaseJsonHttpResponseHandler
15.支持SAX解析SaxAsyncHttpResponseHandler
16.支持多语言,不止UTF8
top榜上的应用
。。。
安装和使用
安装
compile 'com.loopj.android:android-async-http:1.4.5'
包含
import com.loopj.android.http.*;
创建一个异步的请求
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://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 client
创建静态的一个Httpclient类
import com.loopj.android.http.*; public class TwitterRestClient { private static final String BASE_URL = "http://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; } }
很方便的使用
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); } }); } }
更多的可以看文档: AsyncHttpClient, RequestParams and AsyncHttpResponseHandler
持续的Cookie的存储 PersistentCookieStore
库中包含PersistentCookieStore是实现了Apache的HttpClient的CookieStore接口,会自动持续存储
下面是一个例子:
AsyncHttpClient myClient = new AsyncHttpClient(); //设置要存储的Cookie对象 PersistentCookieStore myCookieStore = new PersistentCookieStore(this); myClient.setCookieStore(myCookieStore); //等收到响应的时候,对象会自动存储起来。 //还可以自己添加cookie
更多的看 PersistentCookieStore Javadoc
添加 参数
RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data"); //方法二 RequestParams params = new RequestParams("single", "value"); //方法三 HashMap<String, String> paramMap = new HashMap<String, String>(); paramMap.put("key", "value"); RequestParams params = new RequestParams(paramMap);
See the RequestParams Javadoc for more information.
上传文件(RequestParams)
可进行多文件上传
//以流的形式 InputStream myInputStream = blah; RequestParams params = new RequestParams(); params.put("secret_passwords", myInputStream, "passwords.txt"); //以File文件 File myFile = new File("/path/to/file.png"); RequestParams params = new RequestParams(); try { params.put("profile_picture", myFile); } catch(FileNotFoundException e) {} //以byte[] byte[] myByteArray = blah; RequestParams params = new RequestParams(); params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
See the RequestParams Javadoc for more information.
下载二进制文件(FileAsyncHttpResponseHandler)
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, File response) { // Do something with the file `response` } });
See the FileAsyncHttpResponseHandler Javadoc for more information.
添加http基本授权认证
很多请求要带有 用户名/密码 授权。
AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password/token"); client.get("http://example.com"); AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM)); client.get("http://example.com");
See the RequestParams Javadoc for more information.
结束
相关推荐
// 1.创建异步请求的客户端对象 ...其他有什么问题或者想具体了解详细说明,可以参考官网 http://loopj.com/android-async-http/ 其他参考链接 http://blog.csdn.net/redarmy_chen/article/details/26980613
Asynchronous Http Client for Android 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...
Android Asynchronous HTTPClient的实现和优化
This library requires Android Asynchronous Http Client by James Smith. You have to maintain cookies with com.loopj.android.http.PersistentCookieStore class. Or you can try my fork of Android ...
An Asynchronous Socket Server and Client
"Asynchronous Android Programming" English | ISBN: 1785883240 | 2016 | 394 pages About This Book Construct scalable and performant applications to take advantage of multi-thread asynchronous ...
Asynchronous Android Programming 2nd 第2版 英文pdf
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 ...
框架目前主要包含的功能有View ...UltimateAndroid框架是如同flask框架(python)那样包含了许多其他的开源项目的框架,比如 Butter Knife,Asynchronous Http Client for Android, Universal Image Loader for Android
cc.itbox.babysay.activities |--BaseActivity 基类Activity |--GuideActivity 引导页Activity ... Android Asynchronous Http Client Holoeverywhere SmoothProgressBar ActionBar-PullToRefresh
Python库模块“ asynchat”的扩展,以支持高度可扩展的HTTP客户端。 我们打算学习并使用出色的“ httplib”模块。
Telemecanique Premium Atrium asynchronous links 用户手册(英文)pdf,Telemecanique Premium Atrium asynchronous links 用户手册(英文)
Asynchronous programming has acquired immense importance in Android programming, especially when we want to make use of the number of independent processing units (cores) available on the most recent ...
1.Android Asynchronous Http Client 2.okhttp square开发并且开源的,因为之前用过他们家的picasso,所以对这套满有好感的,只可惜使用方式不太喜欢 3.Volley Volley是Google在2013年Google I/O的时候发布的,到...
代码是基于loopj (Asynchronous Http Client for Android) 的文件上传Demo,loopj 是基于 Apache's HttpClient 的异步http客户端。
Telemecanique Unity Pro编程的Modicon Premium的Asynchronous serial link的用户手册(2005-英文)zip,Telemecanique Unity Pro编程的Modicon Premium的Asynchronous serial link的用户手册(2005-英文)
Using it, you can easily create an asynchronous HTTP request and receive event callback. It can be applied to MFC and ATL projects. This code mainly consists of two classes: class FCHttpRequest and ...
Since the JavaScript language is single threaded, Node.js programs must make use of asynchronous callbacks and event loops managed by the runtime to ensure appli- cations remain responsive....
A cross-platform asynchronous HTTP(S) proxy server in C#.