Android Asynchronous Http Client

来源:互联网 发布:书生阅读软件 编辑:程序博客网 时间:2024/05/23 15:32

官方地址,文档地址:

本文只是官方文档的简单翻译:

概述:

以Apache的HttpClient 库为基础, 所有的网络请求都在UI线程外,回调事件处理在UI线程中(类似Android中的Handler处理方式)。你可以在Service或后台线程中执行网络操作,我们可以自动识别Context。 

特点:

· UI线程外执行HTTP 请求

· 是用来一个Requests线程池来限制资源并发使用

· GET/POST params builder (RequestParams)

· 文件上传无需第三方包支持(Multipart file uploads 

· 不需要第三方库支持上传JSON流 

· 自动处理循环与重定向 

· 库文件非常小,只有90Kb 

· 针对移动端参差不齐的网络环境,自动智能的重试 

· 自动采用gzip压缩方式 

· 二进制协议 BinaryHttpResponseHandler

· 使用 FileAsyncHttpResponseHandler将网络响应直接保存到文件中 

· SharedPreferences 中永久保存cookie 

· BaseJsonHttpResponseHandler支持Jackson JSON, Gson or other JSON

· Support for SAX parser with SaxAsyncHttpResponseHandler

· 支持语言与内容选择编码,不仅仅是UTF-8

基本使用:

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;  }}
在代码中使用:

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

保存Cookie

使用PersistentCookieStore 类,其实现了Apache HttpClient CookieStore接口,可以将cookies永久保存在SharedPreferences中。如果要处理身份验证,这相当有用。

AsyncHttpClient myClient = new AsyncHttpClient();//新建一个PersistentCookieStore对象,可以传Activity或context(最好是context)PersistentCookieStore myCookieStore = new PersistentCookieStore(this);myClient.setCookieStore(myCookieStore);//也可以手动添加BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");newCookie.setVersion(1);newCookie.setDomain("mydomain.com");newCookie.setPath("/");myCookieStore.addCookie(newCookie);

RequestParams

看名字就知道了,是一个添加请求参数的一个类:

1.创建一个空的 RequestParams,添加参数 

RequestParams params = new RequestParams();params.put("key", "value");params.put("more", "data");
2. 只包含一个参数: 

RequestParams params = new RequestParams("single", "value");
3.Map集合中建立一个RequestParams
HashMap<String, String> paramMap = new HashMap<String, String>();paramMap.put("key", "value");RequestParams params = new RequestParams(paramMap);

上传文件

RequestParams 类支持文件上传,看下例子吧

1.使用InputStream

InputStream myInputStream = blah;RequestParams params = new RequestParams();params.put("secret_passwords", myInputStream, "passwords.txt");
2.使用一个File对象
File myFile = new File("/path/to/file.png");RequestParams params = new RequestParams();try {    params.put("profile_picture", myFile);} catch(FileNotFoundException e) {}
3.使用 byte数组
byte[] myByteArray = blah;RequestParams params = new RequestParams();params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

下载文件

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

Http基础验证

一些请求需要用户名/密码来进行验证,可以使用 setBasicAuth() 方法,默认允许所有的主机,最好设置下:

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




0 0