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
  • Streamed JSON uploads with no additional libraries
  • Handling circular and relative redirects
  • Tiny size overhead to your application, only 90kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Binary protocol communication with BinaryHttpResponseHandler
  • Built-in response parsing into JSON with JsonHttpResponseHandler
  • Saving response directly into file with FileAsyncHttpResponseHandler
  • Persistent cookie store, saves cookies into your app’s SharedPreferences
  • Integration with Jackson JSON, Gson or other JSON (de)serializing libraries withBaseJsonHttpResponseHandler
  • Support for SAX parser with SaxAsyncHttpResponseHandler
  • Support for languages and content encodings, not just UTF-8

Used in Production By Top Apps and Developers

Instagram
Instagram is the #1 photo app on android, with over 10million users
Pinterest
Popular online pinboard. Organize and share things you love.
Frontline Commando (Glu Games)
#1 first person shooting game on Android, by Glu Games.
Heyzap
Social game discovery app with millions of users
Pose
Pose is the #1 fashion app for sharing and discovering new styles
Thousands more apps…
Async HTTP is used in production by thousands of top apps.

Installation & Basic Usage

Add maven dependency using Gradle buildscript in format

dependencies {
compile 'com.loopj.android:android-async-http:1.4.5'
}

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

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

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 toSharedPreferences 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 calladdCookie:

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 FileAsyncHttpResponseHandler

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

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {
@Override
public void onSuccess(int statusCode, Header[] headers, File response) {
// Do something with the file `response`
}
});

See the FileAsyncHttpResponseHandler 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.

Testing on device

You can test the library on real device or emulator using provided Sample Application. Sample application implements all important functions of library, you can use it as source of inspiration.

Source code of sample application: https://github.com/loopj/android-async-http/tree/master/sample

To run sample application, clone the android-async-http github repository and run command in it’s root:

gradle :sample:installDebug

Which will install Sample application on connected device, all examples do work immediately, if not please file bug report on https://github.com/loopj/android-async-http/issues

Building from Source

To build a .jar file from source, first make a clone of the android-async-http github repository. Then you have to have installed Android SDK and Gradle buildscript, then just run:

gradle :library:jarRelease

This will generate a file in path {repository_root}/library/build/libs/library-1.4.6.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
Marek Sebera (http://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 (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

And many others, contributions are listed in each file in license header. You can also find contributors by looking on project commits, issues and pull-requests onGithub

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 Asynchronous Http Client的更多相关文章

  1. Android Asynchronous Http Client 中文教程

    本文为译文,原文链接https://loopj.com/android-async-http/ 安卓异步httpclient 概述 这是一个异步的基于回调的Android http客户端,构建于Apa ...

  2. Android手机SSH Client客户端推荐JuiceSSH

    Windows上建立ssh服务器 参见: http://www.cnblogs.com/xred/archive/2012/04/21/2461627.html Android手机SSH Client ...

  3. Android开源库--Asynchronous Http Client异步http客户端

    如果说我比别人看得更远些,那是因为我站在了巨人的肩上. github地址:https://github.com/loopj/android-async-http Api文档地址:http://loop ...

  4. Android 网络提交数据(使用Asynchronous Http Client)

    项目主页及简单使用方法http://loopj.com/android-async-http/ 页面布局就不复制了,把主要的Activity记录下来,供自己以后使用: package com.exam ...

  5. android studio This client is too old to work with the working copy at

    http://www.cnblogs.com/maijin/archive/2013/01/09/2852330.html http://stackoverflow.com/questions/283 ...

  6. Android Asynchronous Http Client-Android异步网络请求客户端接口

    1.简介 Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用and ...

  7. TeleMCU视频会议之Android版本号WebRTC client支持

    本文原创自 http://blog.csdn.net/voipmaker  转载注明出处. 最新版本号TeleMCU 添加了Android手机端WebRTC视频会议能力,Android手机安装Chro ...

  8. Asynchronous MQTT client library for C (MQTT异步客户端C语言库-paho)

    原文:http://www.eclipse.org/paho/files/mqttdoc/MQTTAsync/html/index.html MQTT异步客户端C语言库   用于C的异步 MQTT 客 ...

  9. Java Android HTTP实现总结

    Java Android HTTP实现总结 Http(Hypertext Transfer Protocol)超文本传输协议,是一个基于请求/响应模式的无状态的协议,Http1.1版给出了持续连接的机 ...

随机推荐

  1. 杭电acm 1040题

    本题是一个非常简单的升序排序题目,但那时在做的时候把题目看错了,导致花费了大量的时间来检查为什么WA,最后发现题目看错了..... /********************************* ...

  2. 关于android上dpi/screen-size的厘清解释

    android定义了四种screen-size: small normal large xlarge 同时定义了六种dpi级别: ldpi (low) ~120dpimdpi (medium) ~16 ...

  3. R: 时间处理(R自带函数)

    ################################################### 问题:时间处理    18.4.28 如何用,as.Date()规范日期.计算日期的加减等?? ...

  4. Spring入门第二十九课

    事务的隔离级别,回滚,只读,过期 当同一个应用程序或者不同应用程序中的多个事务在同一个数据集上并发执行时,可能会出现许多意外的问题. 并发事务所导致的问题可以分为下面三种类型: -脏读 -不可重复读 ...

  5. 5.Windows应急响应:挖矿病毒

    0x00 前言 随着虚拟货币的疯狂炒作,挖矿病毒已经成为不法分子利用最为频繁的攻击方式之一.病毒 传播者可以利用个人电脑或服务器进行挖矿,具体现象为电脑CPU占用率高,C盘可使用空间骤降, 电脑温度升 ...

  6. 1.Windows入侵排查思路

    0x00 前言 当企业发生黑客入侵.系统崩溃或其它影响业务正常运行的安全事件时,急需第一时间进行处理,使企业的网络信息系统在最短时间内恢复正常工作,进一步查找入侵来源,还原入侵事故过程,同时给出解决方 ...

  7. 微信小程序小结(1) ------ 前后端交互及wx.request的简易封装

    微信小程序的应用目前越来越多,不管喜欢与否我们都应该了解一些.废话不多,直接干货. 做项目自然避免不了前后端的交互,小程序在调试过程中需要在先在:小程序公众平台--设置--开发设置中,将要从后台请求的 ...

  8. 在eclipse中打开文件所在的目录

    eclipse中默认是不能直接打开文件所在的目录的,需要在文件中右键-->properties-->location,复制到资源管理器中才能打开文件所在的目录.这种方法很麻烦.这里介绍一种 ...

  9. 问题:Tomcat启动产生错误严重: Error initializing endpoint java.lang.Exception

    1问题描述: Tomcat启动产生错误严重: Error initializing endpoint java.lang.Exception: Socket bind failed: [730048] ...

  10. Git练习3 远程库分支 idea中状态条显示当前分支