Android Asynchronous Http Client

原文:http://loopj.com/android-async-http/

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?

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 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 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 ofPersistentCookieStore,
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

I'm James Smith, CTO of heyzap.com.
Originally from London, UK I now live in San Francisco.

时间: 2024-10-23 19:59:41

Android Asynchronous Http Client的相关文章

Android Asynchronous HTTPClient的实现和优化

大家知道Android对UI线程的反应时间要求很高,超过5秒钟直接ANR掉,根本不给你机会多等. 而Android应用与后端系统的交互是最基本的需求之一,如何实现高效的Asynchronous HTTPClient,确保UI线程在启动任务后交由后端异步处理与服务器端的通信,尤为关键. Google过几个方案,要么太复杂要么不符合要求,基本都淘汰了,最后发现这一版本的实现不错,就拿来用了. 链接:Android Asynchronous HTTPClient tutorial 后来发现了几个严重的

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

1.简介Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-async-http这个库可以大大的简化操作,它是基于Apache's HttpClient ,所有的请求都是独立在UI主线程之外,通过回调方法处理请求结果,采用android  Handler message 机制传递信息. 2.特性(1)采用异步http请求,并通过匿名内部类处理回调结果

Android的HTTP操作库Volley的基本使用教程_Android

以前原本都用android内建的Library来进行GET.POST等等对API的连线与操作. 但最近想说来找找看有没有好用的library,应该可以事半功倍. 当初有找了三套比较多人用的 1.Android Asynchronous Http Client 2.okhttp square开发并且开源的,因为之前用过他们家的picasso,所以对这套满有好感的,只可惜使用方式不太喜欢 3.Volley Volley是Google在2013年Google I/O的时候发布的,到现在已经积累了很高的

android-asynchronous http client 的使用

问题描述 asynchronous http client 的使用 官网建议使用静态的对象,static,但是这个如果有多个http请求,会涉及到函数重入的问题,这个明显是不可重入的,官网为什么还要推荐静态使用? 解决方案 没有具体看里里里面的源码,但官网既然推荐用static,应该是表示http client 是线程安全的. static 会减少每次创建对象对性能的影响,可提高性能. 解决方案二: 使用Android Asynchronous Http Client体会Android 网络提交

Android 几种网络请求的区别与联系

HttpUrlConnection 最开始学android的时候用的网络请求是HttpUrlConnection,当时很多东西还不知道,但是在android 2.2及以下版本中HttpUrlConnection存在着一些bug,所以建议在android 2.3以后使用HttpUrlConnection,之前使用HttpClient. 在Android 2.2版本之前,HttpClient拥有较少的bug,因此使用它是最好的选择.而在Android 2.3版本及以后,HttpURLConnecti

Android的HTTP操作库Volley的基本使用教程

以前原本都用android内建的Library来进行GET.POST等等对API的连线与操作. 但最近想说来找找看有没有好用的library,应该可以事半功倍. 当初有找了三套比较多人用的 1.Android Asynchronous Http Client 2.okhttp square开发并且开源的,因为之前用过他们家的picasso,所以对这套满有好感的,只可惜使用方式不太喜欢 3.Volley Volley是Google在2013年Google I/O的时候发布的,到现在已经积累了很高的

根据不同需求跳转不同Activity的另外一种写法

代码如下:   /* Android Asynchronous Http Client Sample Copyright (c) 2014 Marek Sebera <marek.sebera@gmail.com> http://loopj.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wit

Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析_Android

     在上一篇文章中,我们分析了Android系统进程间通信机制Binder中的Server在启动过程使用Service Manager的addService接口把自己添加到Service Manager守护过程中接受管理.在这一篇文章中,我们将深入到Binder驱动程序源代码去分析Client是如何通过Service Manager的getService接口中来获得Server远程接口的.Client只有获得了Server的远程接口之后,才能进一步调用Server提供的服务.       

Android编程实现简单的UDP Client实例_Android

本文实例讲述了Android编程实现简单的UDP Client.分享给大家供大家参考,具体如下: 该代码在4.2.2内调试通过 1.记得加权限 <uses-permission android:name="android.permission.INTERNET"/> 注意:Android 4.0之后,就不能在主线程进行socket通信,否则会抛异常. 2.代码 MainActivity.java: package mao.example.quicksend; import