安卓异步代理服务器客户端理解


Android Asynchronous Http Client

A Callback-Based Http Client Library for Android

安卓异步代理服务器客户端

一个基于为安卓回调客户端库



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.

异步基于回调的Http客户端为Android之上的Apache HttpClient库。所有请求都是你的app主要UI线程之外建立的,但任何回调逻辑将相同的线程上执行回调使用Android的处理程序创建消息传递。


Features

特点

  • Make   asynchronous  HTTP requests, handle responses in   anonymous callbacks
  • 进行异步HTTP请求,处理响应在匿名回调
  • HTTP requests happen   outside the UI thread
  • HTTP请求发生在UI线程之外
  • Requests use a   threadpool  to cap concurrent resource usage
  • 请求使用threadpool能够遮盖并发资源使用情况
  • GET/POST   params builder  (RequestParams)
  • GET / POST参数构造器(RequestParams)
  • Multipart file uploads  with no additional third party libraries
  • 多部分文件上传,没有额外的第三方库
  • Tiny size overhead to your application, only   25kb  for everything
  • 对于你的程序,只能有很少的大小超过,对于整个项目来说只能超过25kb
  • Automatic smart   request retries  optimized for spotty mobile connections
  • 移动智能连接请求对于移动连接参数不齐
  • Automatic   gzip  response decoding support for super-fast requests
  • 自动解码支持gzip反应速度超快的请求
  • Binary file (images etc) downloading with   BinaryHttpResponseHandler
  • 二进制文件(图片等)与BinaryHttpResponseHandler下载
  • Built-in response parsing into   JSON  with   JsonHttpResponseHandler
  • 内置的解析与JsonHttpResponseHandler JSON响应
  • Persistent cookie store, saves cookies into your app’s SharedPreferences
  • 持久化cookie存储、保存cookie到你的应用程序的SharedPreferences

Used in Production By Top Apps and Developers

用于生产高级应用程序和开发人员进行开发时进行使用


Instagram is the #1 photo app on android, with over 10million users
Instagram是排名第一的照片应用在android上,拥有超过1000万用户
Popular online pinboard. Organize and share things you love.
受欢迎的在线插接板。 组织和分享你喜欢的事情。
#1 first person shooting game on Android, by Glu Games.
排名第一的以一人称射击游戏在Android上,Glu游戏。
Social game discovery app with millions of users
一个拥有数以百万计的用户社交游戏应用程序
Pose is the #1 fashion app for sharing and discovering new styles
Pose是排名第一的时尚应用分享和发现新的风格的应用程序
数以千计的甚至更多的应用程序
Async HTTP is used in production by thousands of top apps.
异步HTTP是用于生产成千上万的应用程序的(一种工具)

Installation & Basic Usage

安装和基本使用

Download the latest .jar file from github and place it in your Android app’s libs/ folder.

Import the http package.

下载最新款的jar文件来自于github并且将它放置在你的安卓app的libs的文件夹下一级目录,导入http包

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

推荐用法:创建一个静态的Http用户

In this example, we’ll make a http client class with static accessors to make it easy to communicate with Twitter’s API.

在本例中,我们将做一个http客户机类静态访问器使它容易与Twitter的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:

这使得它很容易使用Twitter API代码:

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.

查看AsyncHttpClient,RequestParams AsyncHttpResponseHandlerJavadocs能够查出更多的细节方面的问题。

与PersistentCookieStore持久化Cookie存储

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.

这个库还包含一个PersistentCookieStore Apache HttpClient CookieStore接口的一个实现方法,自动保存cookie SharedPreferences存储在Android设备上。

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.

这是非常有用的,如果你想使用cookie来管理身份验证会话,因为用户将继续登录即使关闭并重启应用程序

First, create an instance of AsyncHttpClient:

首先,创建一个实例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):

现在将这个客户的cookie存储PersistentCookieStore的一个新实例,构造一个活动或应用程序上下文(通常这就足够了):

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);

Any cookies received from servers will now be stored in the persistent cookie store.

任何收到服务器将存储在cookie持久性cookie存储。

To add your own cookies to the store, simply construct a new cookie and call addCookie:

添加自己的cookies到商店,只需构建一个新的cookies和叫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.

看到PersistentCookieStore Javadoc以获取更多信息。

Adding GET/POST Parameters with RequestParams

利用RequestParams添加GET / POST参数

The RequestParams class is used to add optional GET or POST parameters to your requests.RequestParams can be built and constructed in various ways:

RequestParams类是用于添加可选的GET或POST请求参数。RequestParams可以以各种方式建造而成:

Create empty RequestParams and immediately add some parameters:

建立空RequestParams并立即添加一些参数:

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

Create RequestParams for a single parameter:

创建RequestParams为单个参数:

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

Create RequestParams from an existing Map of key/value strings:

从现有的Map创建RequestParams键/值的字符串:

HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);

See the RequestParams Javadoc for more information.

看到RequestParams Javadoc以获取更多信息。

Uploading Files with RequestParams

上传文件RequestParams

The RequestParams class additionally supports multipart file uploads as follows:

另外RequestParams类支持多部分文件上传,如下所示:

Add an InputStream to the RequestParams to upload:

添加InputStream RequestParams上传:

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:

添加一个文件对象RequestParams上传:

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

See the RequestParams Javadoc for more information.

看到RequestParams Javadoc以获取更多信息。

Downloading Binary Data with BinaryHttpResponseHandler

与BinaryHttpResponseHandler下载二进制数据

The BinaryHttpResponseHandler class can be used to fetch binary data such as images and other files. For example:

BinaryHttpResponseHandler类可以用来获取二进制数据,如图像和其他文件。例如:

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.

看到RequestParams Javadoc以获取更多信息。

Adding HTTP Basic Auth credentials

添加HTTP基本身份验证凭据

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.

一些请求可能需要用户名/密码凭据在处理API使用HTTP基本身份验证请求访问的服务。您可以使用方法setBasicAuth()提供您的凭据。

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.

看到RequestParams Javadoc以获取更多信息。

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:

建立一个.jar文件从源码包中,首先做一个克隆的android-async-httpgithub库。然后,您需要复制local.properties.dist文件到ocal.properties和编辑sdk。dir设置指向你安装了android sdk。然后,您可以运行:

ant package

This will generate a file named android-async-http-version.jar.

这将生成一个名为android-async-http-version.jar的文件。

Reporting Bugs or Feature Requests

报告bug或特性请求

Please report any bugs or feature requests on the github issues page for this project here:

https://github.com/loopj/android-async-http/issues

请报告任何错误或特性请求在github问题页面对于这个项目:https://github.com/loopj/android-async-http/issues


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值