Android Asynchronous Http Client

A Callback-Based Http Client Library for Android

  Tweet

Overview

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI
thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing.

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 25kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Binary file (images etc) downloading with BinaryHttpResponseHandler
  • Built-in response parsing into JSON with JsonHttpResponseHandler
  • Persistent cookie store, saves cookies into your app’s SharedPreferences

Who is Using It?

Instagram
Instagram is the #1 photo app on android, with over 10million users
Heyzap
Social game discovery app with millions of users
DoubanFM
Popular personal online music radio service
Pose
Pose is the #1 fashion app for sharing and discovering new styles
Pocket Salsa
Pocket Salsa is the easiest way to learn how to dance salsa.

Send me a message on github to let me know if you are using this library in a released android application!

Installation & Basic Usage

Download the latest .jar file from github and place it in your Android app’s libs/ folder.

Import the http package.

import com.loopj.android.http.*;

Create a new AsyncHttpClient instance and make a request:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});

Recommended Usage: Make a Static Http Client

In this example, we’ll make a http client class with static accessors to make it easy to communicate with Twitter’s API.

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

This then makes it very easy to work with the Twitter API in your code:

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

Check out the AsyncHttpClientRequestParams and AsyncHttpResponseHandlerJavadocs
for more details.

Persistent Cookie Storage with PersistentCookieStore

This library also includes a PersistentCookieStore which is an implementation of the Apache HttpClient CookieStore interface
that automatically saves cookies to SharedPreferences storage on the Android device.

This is extremely useful if you want to use cookies to manage authentication sessions, since the user will remain logged in even after closing and re-opening your app.

First, create an instance of AsyncHttpClient:

AsyncHttpClient myClient = new AsyncHttpClient();

Now set this client’s cookie store to be a new instance of PersistentCookieStore, constructed with an activity or application
context (usually this will suffice):

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

Any cookies received from servers will now be stored in the persistent cookie store.

To add your own cookies to the store, simply construct a new cookie and call addCookie:

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

See the PersistentCookieStore Javadoc for more information.

Adding GET/POST Parameters with RequestParams

The RequestParams class is used to add optional GET or POST parameters to your requests.RequestParams can
be built and constructed in various ways:

Create empty RequestParams and immediately add some parameters:

RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");

Create RequestParams for a single parameter:

RequestParams params = new RequestParams("single", "value");

Create RequestParams from an existing Map of
key/value strings:

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

See the RequestParams Javadoc for more information.

Uploading Files with RequestParams

The RequestParams class additionally supports multipart file uploads as follows:

Add an InputStream to the RequestParams to
upload:

InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");

Add a File object to the RequestParams to
upload:

File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

Add a byte array to the RequestParams to upload:

byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

See the RequestParams Javadoc for more information.

Downloading Binary Data with BinaryHttpResponseHandler

The BinaryHttpResponseHandler class can be used to fetch binary data such as images and other files. For example:

AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) {
@Override
public void onSuccess(byte[] fileData) {
// Do something with the file
}
});

See the BinaryHttpResponseHandler Javadoc for more information.

Adding HTTP Basic Auth credentials

Some requests may need username/password credentials when dealing with API services that use HTTP Basic Access Authentication requests. You can use the method setBasicAuth()to
provide your credentials.

Set username/password for any host and realm for a particular request. By default the Authentication Scope is for any host, port and realm.

AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password/token");
client.get("http://example.com");

You can also provide a more specific Authentication Scope (recommended)

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.

Building from Source

To build a .jar file from source, first make a clone of the android-async-http github repository. You’ll then need to
copy the local.properties.dist file to local.properties and
edit the sdk.dir setting to point to where you have the android sdk installed. You can then run:

ant package

This will generate a file named android-async-http-version.jar.

Reporting Bugs or Feature Requests

Please report any bugs or feature requests on the github issues page for this project here:

https://github.com/loopj/android-async-http/issues

Credits & Contributors

James Smith (http://github.com/loopj)
Creator and Maintainer
Micah Fivecoate (http://github.com/m5)
Major Contributor, including the original RequestParams
The Droid Fu Project (https://github.com/kaeppler/droid-fu)
Inspiration and code for better http retries
Rafael Sanches (http://blog.rafaelsanches.com)
Original SimpleMultipartEntity code
Anthony Persaud (http://github.com/apersaud)
Added support for HTTP Basic Authentication requests.
Linden Darling (http://github.com/coreform)
Added support for binary/image responses

License

The Android Asynchronous Http Client is released under the Android-friendly Apache License, Version 2.0. Read the full license here:

http://www.apache.org/licenses/LICENSE-2.0

About the Author

James Smith, British entrepreneur and developer based in San Francisco.

I'm the co-founder of Bugsnag with Simon Maynard, and from 2009 to 2012 I led up the product team as
CTO of Heyzap.

Follow @loopj

Android AsyncHttpClient的更多相关文章

  1. android AsyncHttpClient 开源框架的使用

    AsyncHttpClient 1.在很多时候android都需要进行网络的操作,而android自带的HttpClient可以实现,但要进行很多网络连接的时候(如:下载很多图片),就需要线程池来进行 ...

  2. android AsyncHttpClient使用

    1.www.github.com下载jar包 loopj/android-async-http 将下载好的文件导入项目中 2.main.xml <?xml version="1.0&q ...

  3. android和httpClient

    一.说起来都是泪 各大组织不同步,可是我想用别人的库. 二.谷歌和阿帕奇的爱恨情仇 初,谷歌安卓新出,库中自带HttpClient 4.0测试预览版.为与安卓保持API同步,HTTPClient不敢大 ...

  4. android 6.0 SDK中删除HttpClient的相关类的解决方法

    一.出现的情况 在eclipse或 android studio开发, 设置android SDK的编译版本为23时,且使用了httpClient相关类的库项目:如android-async-http ...

  5. Android应用中使用AsyncHttpClient来异步网络数据(转载)

    摘要: 首先下载AsyncHttpClient的库文件,可以自行搜索,可以到下面地址下载 http://download.csdn.net/detail/xujinyang1234/5767419 测 ...

  6. Android应用中使用AsyncHttpClient来异步网络数据

    首先下载AsyncHttpClient的库文件,可以自行搜索,可以到下面地址下载 http://download.csdn.net/detail/xujinyang1234/5767419 测试的Ac ...

  7. Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)

    最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所 ...

  8. android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件

    AsyncHttpClient开源框架android-async-http还是非常方便的. AsyncHttpClient该类通经常使用在android应用程序中创建异步GET, POST, PUT和 ...

  9. 【转】Android应用中使用AsyncHttpClient来异步网络数据

    摘要: 首先下载AsyncHttpClient的库文件,可以自行搜索,可以到下面地址下载 http://download.csdn.net/detail/xujinyang1234/5767419 测 ...

随机推荐

  1. Boost库学习之旅入门篇

    学习及使用Boost库已经有一段时间了,Boost为我的日常开发中带来了极大的方便,也使得我越来越依赖于boost库了.但boost功能太多,每次使用还是得翻看以前的 资料,所以为了以后可以更方便的使 ...

  2. linux命令之mv

    linux下的mv即move的意思 该命令的一般形式: mv [选项] 参数1 参数2 选项: -b                如果已存在相同文件名,则覆盖前进行备份 -f             ...

  3. 首次登录与在线求助man page

    为了避免瞬间断电造成的Linux系统损害,建议作为服务器的Linux主机应该加上不断电系统来持续提供稳定的电力. 在终端环境中,可依据提示符为$或#判断为一般几号或root账号. 要取得终端支持的语言 ...

  4. hdu 5501 The Highest Mark(贪心+01背包)

    题意:类似cf的赛制,每道题目有A,B,C三个值,A表示初始分数,B表示每分钟题的分数会减少B,C表示做这道题需要C分钟,数据保证分数不会变为负数.现在给出比赛时长,问安排做题的顺序,求最大得分. 思 ...

  5. Mysql数据库启动

    1.改变数据库的访问ip: vim /etc/mysql/my.cnf 找到下面选项: bind-address            = 192.168.1.128 修改即可. 2.mysql启动命 ...

  6. 聚类算法初探(五)DBSCAN

    最近由于工作需要,对聚类算法做了一些相关的调研.现将搜集到的资料和自己对算法的一些理解整理如下,供大家参考. 另外在算法代码方面,我也做了一些实现(包括串行和并行),欢迎感兴趣的朋友探讨和交流. 第一 ...

  7. Hibernate征途(二)之基础与核心

    根据我司优良传统,必然要由上向下.逐级深入,所以在钻到Hibernate细节之前,先从宏观上行欣赏一下Hibernate.为什么说是欣赏?大家可以自行查阅一下Hibernate知识外的信息,创始人和H ...

  8. Slf4j的包冲突

    异常信息:Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.log4j.Log4jLog ...

  9. 使用fat jar和exe4j把java程序打包成exe执行文件---转载的

    java应用编写测试好之后都是jar包或class文件,客户拿到这个东西后一般是不会java开发者那样在命令窗口下面输入运行的.客户要求的就是直接点击应用名称运行.java在方面做得很不友好,开发人员 ...

  10. Silverlight学习(二)

    好久没来写博客了,这期间经历了春节,也因为忙于一个项目,所以博客被疏忽了.最近一段时间一直在用silverlight做项目,从来一开始的不熟悉渐渐的开始上手.今天记录一下自己学习prism的一些sam ...