博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android AsyncHttpClient
阅读量:6550 次
发布时间:2019-06-24

本文共 8778 字,大约阅读时间需要 29 分钟。

  

or 

Overview

An asynchronous callback-based Http client for Android built on top of Apache’s  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 is the #1 photo app on android, with over 10million users
Social game discovery app with millions of users
Popular personal online music radio service
Pose is the #1 fashion app for sharing and discovering new styles
Pocket Salsa is the easiest way to learn how to dance salsa.

Send me a  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); }});

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 ,  and Javadocs for more details.

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  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
paramMap = new HashMap
();paramMap.put("key", "value");RequestParams params = new RequestParams(paramMap);

See the  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  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  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  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:

Credits & Contributors

James Smith ( )
Creator and Maintainer
Micah Fivecoate ( )
Major Contributor, including the original 
RequestParams
The Droid Fu Project ( )
Inspiration and code for better http retries
Rafael Sanches ( )
Original 
SimpleMultipartEntity code
Anthony Persaud ( )
Added support for HTTP Basic Authentication requests.
Linden Darling ( )
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:

About the Author

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

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

转载地址:http://touco.baihongyu.com/

你可能感兴趣的文章
神奇的代码-常见错误代码注意点
查看>>
[直播一揽子]编码构思和套路
查看>>
[直播一揽子]x264参数的解释
查看>>
iOS学习之Objective-C 2.0 运行时系统编程
查看>>
Exchange2007-Exchange2010升级-06 数据库高可用组的创建
查看>>
phpHiveAdmin是如何通过Hive/Hadoop工作的
查看>>
双向链表内结点的删除(4)
查看>>
项目总结
查看>>
JSON字符串转成对象
查看>>
SaltStack 中ZMQ升级
查看>>
exchange 2013 提示“HTTP 500内部服务器错误”
查看>>
Linux运维学习笔记之一:运维的原则和学习方法
查看>>
怎样使用原型设计中的组件样式功能
查看>>
python threading
查看>>
谷安天下2013年6月CISA考前辅导 第一季
查看>>
在普通台式机上搭建服务器虚拟化架构Esxi平台
查看>>
电话线路 30B+D 名词解释
查看>>
吉炬消费系统软件输入密码后无法打开软件界面故障处理
查看>>
Hibernate学习系列————注解一对多双向实例
查看>>
Cannot load from mysql.proc
查看>>