Android网络通信之android-async-http入门

android-async-http入门

API原文:http://loopj.com/android-async-http/
***Android Asynchronous Http Client
A Callback-Based Http Client Library for Android***

特征

  • 所有的requested请求都在UI线程之外发起
  • 进行http异步请求时,处理请求响应都在匿名回调函数中
  • 请求使用一个线程池来限制并发资源使用情况
  • get/post参数构建器 (RequestParams)
  • 多文件上传,没有额外的第三方库
  • json流上传,没有额外的第三方库
  • 在你的应用里只要很小的开销,所有的文件只要90kb
  • 自动对超快请求进行gzip响应解码
  • 自动智能的重试优化请求方便质量不一的手机连接
  • 使用FileAsyncHttpResponseHandler把响应直接保存到文件
  • 持久化cookie存储,保存cookie到你的应用程序的SharedPreferences
  • 集成Jackson JSON,Gson或其他JSON(反)序列化库在BaseJsonHttpResponseHandler中
  • SaxAsyncHttpResponseHandler支持SAX解析器
  • 支持语言和内容编码,而不仅仅是utf - 8

在此网站下都是使用AAH库开发的应用,翻墙进去逛逛吧:http://www.appbrain.com/stats/libraries/details/loopj_asynchttpclient/android-asynchronous-http-client

安装和基本用法

http://loopj.com/android-async-http/里下载android-async-http-1.4.6.jar(最新版)并导入到工程中。

import Http包

import com.loopj.android.http.*;

创建一个新的AsyncHttpClient实例和请求:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // called before request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
    }
});

建议用法:静态的Http客户端

在本例中,我们做一个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;
  }
}

这样之后很容易在你的代码中使用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(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, 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);
            }
        });
    }
}

查看AsyncHttpClient,RequestParams,AsyncHttpResponseHandler Javadocs的更多的细节

持久化Cookie存储PersistentCookieStore

这个库还包含一个实现Apache HttpClient CookieStore接口的PersistentCookieStore,自动在Android设备上使用SharedPreferences存储保存cookie。
如果你想使用cookie来管理身份验证会话这是非常有用的,,因为用户将继续登录即使关闭并重启应用程序。

首先,创建一个实例AsyncHttpClient:

AsyncHttpClient myClient = new AsyncHttpClient();

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

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

任何从服务器收到的cookies都会被存储在持久化cookie存储。

添加自己的cookies进行存储,只需构建一个新的cookie和调用addCookie:

BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);

添加GET / POST参数RequestParams

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

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

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

创建一个参数的RequestParams:

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

创建一个存在map键值对的字符串RequestParams:

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

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

加参数RequestParams的文件上传

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

添加一个带有inputStream的requestParams参数用来上传:

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

添加一个带有文件对象的requestParams参数用来上传:

File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

添加一个带有字节数组的requestParams参数用来上传:

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

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

使用FileAsyncHttpResponseHandler下载二进制数据

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

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {
    @Override
    public void onSuccess(int statusCode, Header[] headers, File response) {
        // Do something with the file `response`
    }
});

查看FileAsyncHttpResponseHandler Javadoc以获取更多信息。

添加HTTP基本身份验证信息

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

对任何主机和领域特定的请求设置用户名/密码。默认情况下,认证范围是任何主机,端口和领域。

AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password/token");
client.get("http://example.com");

你还可以提供更具体的认证范围(推荐)

AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("http://example.com");

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

测试设备

你可以在真实的设备或模拟器使用提供的示例应用程序测试库。库的示例应用程序实现了所有重要的功能,你可以使用它作为灵感的源泉。
示例应用程序的源代码:https://github.com/loopj/android-async-http/tree/master/sample
要运行示例应用程序,在它的根克隆android-async-http github库和运行命令:

gradle :sample:installDebug

将在连接的设备上安装示例应用程序,所有示例都会立即工作,如果不是请上传文件错误报告:https://github.com/loopj/android-async-http/issues

下篇文章将会直接进行代码分析。

转载请注明出处

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值