zoukankan      html  css  js  c++  java
  • Android网络通信android-async-http入门

    android-async-http入门

    门免费链接分享前:http://pan.baidu.com/s/1mg9SvgO 密码:cgg7
    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(最新版)并导入到project中。

    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客户端静态类訪问器使它easy与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;
      }
    }

    这样之后非常easy在你的代码中使用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);

    不论什么从server收到的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

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

    转载请注明出处

    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    设计模式学习——前言和目录
    模板颜色搭配
    win7、xp下Meclipse SVN用户名修改
    JS编码解码
    用Javascript进行HTML转义(分享)
    打印异常信息
    lucene 抛出的异常(分享)
    SQL语句优化(分享)
    Java集群之session共享解决方案
    VUE中返回上一页
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4885387.html
Copyright © 2011-2022 走看看