官方网站:http://loopj.com/android-async-http/


源代码下载:https://github.com/loopj/android-async-http


帮助文档:http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html


Who is Using It?

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

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

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 response) {                // 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.

This library also includes aPersistentCookieStorewhich is an implementation of the Apache HttpClientCookieStoreinterface that automatically saves cookies toSharedPreferencesstorage 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 (usuallythiswill 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

TheRequestParamsclass is used to add optional GET or POST parameters to your requests.RequestParamscan be built and constructed in various ways:

Create emptyRequestParamsand immediately add some parameters:

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

CreateRequestParamsfor a single parameter:

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

CreateRequestParamsfrom 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 theRequestParams Javadocfor more information.

Uploading Files withRequestParams

TheRequestParamsclass additionally supports multipart file uploads as follows:

Add anInputStreamto theRequestParamsto upload:

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

Add aFileobject to theRequestParamsto 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 theRequestParamsto upload:

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

See theRequestParams Javadocfor more information.

Building from Source

To build a.jarfile from source, first make a clone of the android-async-http github repository. You’ll then need to copy thelocal.properties.distfile tolocal.propertiesand edit thesdk.dirsetting 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 SimpleMultipartEntitycode


更多相关文章

  1. 最易用的 Android(安卓)HTTP library
  2. 最新android版本对应的API等级
  3. Kotlin(Hello World)
  4. 精选的优秀ROM
  5. 15个开发者最亲睐的Andr​​oid代码编辑器
  6. Android(安卓)Gradle plugin与Gradle 版本对应问题
  7. Android开发,用C#!
  8. Android官方网站关于的tab layout的一个问题
  9. Error:Unable to find toolchain: mips64el-linux-android/prebu

随机推荐

  1. Android(安卓)UI 设计规范
  2. PercentageBar自定义动态柱形图 《IT蓝豹
  3. Android手机亮屏流程分析
  4. Andorid Binder进程间通信---Binder本地
  5. 常用到的Android命令(持续更新)
  6. java.io.IOException: open failed: EINV
  7. Android(安卓)关于 EditText 的一些问题
  8. android仿苹果弹性布局
  9. android android.support.v4.util.Pools
  10. android通过usb读取U盘的方法