Android AsyncHttpClient

Android AsyncHttpClient

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

  

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?

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

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 AsyncHttpClientRequestParams and AsyncHttpResponseHandlerJavadocs 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 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

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.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118596.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 2021年汽车修理工(初级)报名考试及汽车修理工(初级)最新解析「建议收藏」

    2021年汽车修理工(初级)报名考试及汽车修理工(初级)最新解析「建议收藏」题库来源:安全生产模拟考试一点通公众号小程序安全生产模拟考试一点通:美容师(技师)试题及解析参考答案及美容师(技师)考试试题解析是安全生产模拟考试一点通题库老师及美容师(技师)操作证已考过的学员汇总,相对有效帮助美容师(技师)复审考试学员题库来源:安全生产模拟考试一点通公众号小程序安全生产模拟考试一点通:质量员-市政方向-通用基础(质量员)考试题是安全生产模拟考试一点通总题库中生成的一套质量员-市政方向-通用基础(质量员)免费试题,安全生产模拟考试一点通上质量员-市政方向-通用基础(质量员)作业手机同步

    2022年10月2日
    3
  • Linux下netstat命令详解

    Linux下netstat命令详解一、介绍Netstat是控制台命令,是一个监控TCP/IP网络的非常有用的工具,它可以显示路由表、实际的网络连接以及每一个网络接口设备的状态信息。Netstat用于显示与IP、TCP、UDP和ICMP协议相关的统计数据,一般用于检验本机各端口的网络连接情况。 二、输出信息描述执行netstat后输出如下:[root@sy-suz-srv51~]#netstatActiv…

    2022年5月7日
    44
  • CentOS7增加或修改SSH端口号

    CentOS7增加或修改SSH端口号

    2021年10月18日
    51
  • Vue devServer.proxy代理配置详解

    Vue devServer.proxy代理配置详解constproxy require http proxy middleware module exports devServer host localhost targethost port 8080 proxy api 代理器中设置 api 项目中请求路径为 api 的替换为 target proxy api target http

    2025年8月30日
    2
  • 浅谈Android指纹识别技术[通俗易懂]

    浅谈Android指纹识别技术[通俗易懂]浅谈Android指纹识别技术当今时代,随着移动智能手机的普及,指纹解锁早已是手机不可或缺的一个功能。除了现在比较新款的iPhone或者部分手机采用了FaceID之外,人们几乎天天都会用到指纹解锁技术。但你知道指纹解锁技术背后的原理吗?原理指纹识别的前提是对指纹的采集,所以我们首先就应该了解第一步:指纹采集。第一步:指纹采集指纹采集主要分为两种方式:滑动式采集和按压式采集滑动式采集是将手指在传感器上滑过,从而使手机获得手指指纹图像。滑动式采集具有成本相对偏低,而且可以采集大面积图像的优势。但这

    2022年8月10日
    1
  • 错误代码as-3_android studio is currently

    错误代码as-3_android studio is currently解决AS编译报错:Causedby:org.gradle.api.internal.plugins.PluginApplicationException:Failedtoapplyplugin[id‘com.android.application’]编译Android项目时总是遇到以上报错,所以记录一下。解决方法:添加android.overridePathCheck=true就可以了。其实解决的方法可以在EventLog窗口中找到,如图下:从日志第一句可以看出,应该是项目路径包

    2025年8月27日
    7

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号