Android(安卓)AsyncHttpClient
Android Asynchronous Http Client
A Callback-Based Http Client Library for Android
Tweet Downloadversion 1.4.2 (latest)orfork me on github
Overview
An asynchronous callback-based Http client for Android built on top of Apache’sHttpClientlibraries. 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
- MakeasynchronousHTTP requests, handle responses inanonymous callbacks
- HTTP requests happenoutside the UI thread
- Requests use athreadpoolto cap concurrent resource usage
- GET/POSTparams builder(RequestParams)
- Multipart file uploadswith no additional third party libraries
- Tiny size overhead to your application, only25kbfor everything
- Automatic smartrequest retriesoptimized for spotty mobile connections
- Automaticgzipresponse decoding support for super-fast requests
- Binary file (images etc) downloading with
BinaryHttpResponseHandler
- Built-in response parsing intoJSONwith
JsonHttpResponseHandler
- Persistent cookie store, saves cookies into your app’s SharedPreferences
Who is Using It?
- 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 amessageon 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’slibs/
folder.
Import the http package.
import com.loopj.android.http.*;
Create a newAsyncHttpClient
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 theAsyncHttpClient,RequestParamsandAsyncHttpResponseHandlerJavadocs for more details.
Persistent Cookie Storage withPersistentCookieStore
This library also includes aPersistentCookieStore
which is an implementation of the Apache HttpClientCookieStore
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 ofAsyncHttpClient
:
AsyncHttpClient myClient = new AsyncHttpClient();
Now set this client’s cookie store to be a new instance ofPersistentCookieStore
, constructed with an activity or application context (usuallythis
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 thePersistentCookieStore Javadocfor more information.
Adding GET/POST Parameters withRequestParams
TheRequestParams
class is used to add optional GET or POST parameters to your requests.RequestParams
can be built and constructed in various ways:
Create emptyRequestParams
and immediately add some parameters:
RequestParams params = new RequestParams();params.put("key", "value");params.put("more", "data");
CreateRequestParams
for a single parameter:
RequestParams params = new RequestParams("single", "value");
CreateRequestParams
from an existingMap
of key/value strings:
HashMap<String, String> paramMap = new HashMap<String, String>();paramMap.put("key", "value");RequestParams params = new RequestParams(paramMap);
See theRequestParams Javadocfor more information.
Uploading Files withRequestParams
TheRequestParams
class additionally supports multipart file uploads as follows:
Add anInputStream
to theRequestParams
to upload:
InputStream myInputStream = blah;RequestParams params = new RequestParams();params.put("secret_passwords", myInputStream, "passwords.txt");
Add aFile
object to theRequestParams
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 theRequestParams
to upload:
byte[] myByteArray = blah;RequestParams params = new RequestParams();params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
See theRequestParams Javadocfor more information.
Downloading Binary Data withBinaryHttpResponseHandler
TheBinaryHttpResponseHandler
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 theBinaryHttpResponseHandler Javadocfor 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 methodsetBasicAuth()
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 theRequestParams Javadocfor 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 thelocal.properties.dist
file tolocal.properties
and edit thesdk.dir
setting to point to where you have the android sdk installed. You can then run:
ant package
This will generate a file namedandroid-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 ofBugsnagwithSimon Maynard, and from 2009 to 2012 I led up the product team as CTO ofHeyzap.
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer