`
2014马年
  • 浏览: 121916 次
  • 性别: Icon_minigender_1
  • 来自: 晋中
社区版块
存档分类
最新评论

Android Asynchronous Http Client 中文手册 1.4.6

阅读更多

简介

基于Apache的HttpClient 的一个android异步包.

回调逻辑执行的线程 == 创建Callback的线程(不是创建Httpclient的线程)

举例:

 

 new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(LOG_TAG, "Before Request");
                    client.get(Activity.this, URL, headers, null, responseHandler);
                    Log.d(LOG_TAG, "After Request");
                }
            }).start();

//在callback的时候,就要用runOnUiThread

 

 

 

特点:

1.异步请求,匿名回调处理响应

2.http请求在UI线程之外

3.请求试用线程池,共用资源

4.GET/POST 参数构建(RequestParams)

5.多文件上传,并且不需要多余3方库

6.JSON流上传

7.处理循环和定向跳转

8.包只有90k

9.自动重连,根据不同的网络连接方式

10.2进制通讯协议BinaryHttpResponseHandler

11.内置JSON解析JsonHttpResponseHandler

12.文件保存FileAsyncHttpResponseHandler

13。持续cookie存储,保存在SharedPreferences里

14支持多个Json解析,包括GSON,使用BaseJsonHttpResponseHandler

15.支持SAX解析SaxAsyncHttpResponseHandler

16.支持多语言,不止UTF8

 

top榜上的应用

。。。

 

安装和使用

安装

 

compile 'com.loopj.android:android-async-http:1.4.5'

 包含

 

 

import com.loopj.android.http.*;

 创建一个异步的请求

 

 

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 client

创建静态的一个Httpclient类

 

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

 更多的可以看文档: AsyncHttpClientRequestParams and AsyncHttpResponseHandler

 

 

持续的Cookie的存储 PersistentCookieStore

库中包含PersistentCookieStore是实现了Apache的HttpClient的CookieStore接口,会自动持续存储

下面是一个例子:

AsyncHttpClient myClient = new AsyncHttpClient();
//设置要存储的Cookie对象
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
//等收到响应的时候,对象会自动存储起来。
//还可以自己添加cookie

 

更多的看 PersistentCookieStore Javadoc

 

添加 参数

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

//方法二
RequestParams params = new RequestParams("single", "value");

//方法三
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)

可进行多文件上传

//以流的形式
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");

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

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

 See the RequestParams Javadoc for more information.

 

下载二进制文件(FileAsyncHttpResponseHandler)

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

 See the FileAsyncHttpResponseHandler Javadoc for more information.

 

添加http基本授权认证

很多请求要带有 用户名/密码 授权。

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

 See the RequestParams Javadoc for more information.

 

 

结束

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    Android Asynchronous Http Client的用法实例

    // 1.创建异步请求的客户端对象 ...其他有什么问题或者想具体了解详细说明,可以参考官网 http://loopj.com/android-async-http/ 其他参考链接 http://blog.csdn.net/redarmy_chen/article/details/26980613

    Android代码-android-async-http

    Asynchronous Http Client for Android An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries. Changelog See what is new in version 1.4.9 released on 19th...

    Android Asynchronous HTTPClient的实现和优化

    在Android开发中,网络通信是应用的核心功能之一,而`Android Asynchronous HTTPClient`(也称为AsyncHttpClient)是一个流行的库,用于实现异步HTTP请求,它使得开发者可以在不阻塞主线程的情况下执行网络操作,...

    Python Asynchronous HTTP Client-开源

    然而,`asynchat`本身并不直接支持HTTP协议,因此,`Python Asynchronous HTTP Client`库应运而生,它在`asynchat`的基础上,构建了一个更高级别的接口,方便开发者进行HTTP请求操作。 这个库的目标是利用Python的...

    Android代码-CookieVideoView

    This library requires Android Asynchronous Http Client by James Smith. You have to maintain cookies with com.loopj.android.http.PersistentCookieStore class. Or you can try my fork of Android ...

    Asynchronous Android Programming

    "Asynchronous Android Programming" English | ISBN: 1785883240 | 2016 | 394 pages About This Book Construct scalable and performant applications to take advantage of multi-thread asynchronous ...

    Asynchronous Http and WebSocket Client library for Java .zip

    Asynchronous Http and WebSocket Client library for Java

    android-async-http 源码

    Asynchronous Http Client for Android Build Status An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries. Changelog See what is new in version 1.4.9 ...

    An Asynchronous Socket Server and Client

    在IT领域,异步套接字(Asynchronous Socket)服务器和客户端是网络编程中的核心概念,主要用于构建高效、可扩展的通信系统。本项目提供的代码示例深入探讨了这一技术,帮助开发者理解如何在实际应用中实现异步通信...

    Android UltimateAndroid框架 源码

    框架目前主要包含的功能有View ...UltimateAndroid框架是如同flask框架(python)那样包含了许多其他的开源项目的框架,比如 Butter Knife,Asynchronous Http Client for Android, Universal Image Loader for Android

    BabySay项目

    cc.itbox.babysay.activities |--BaseActivity 基类Activity |--GuideActivity 引导页Activity ... Android Asynchronous Http Client Holoeverywhere SmoothProgressBar ActionBar-PullToRefresh

    Asynchronous Android Programming(PACKT,2ed,2016)

    Asynchronous programming has acquired immense importance in Android programming, especially when we want to make use of the number of independent processing units (cores) available on the most recent ...

    Telemecanique Premium Atrium asynchronous links 用户手册(英文).pdf

    Telemecanique Premium Atrium asynchronous links 用户手册(英文)pdf,Telemecanique Premium Atrium asynchronous links 用户手册(英文)

    Asynchronous Android

    本书《Asynchronous Android》主要讲述了在Android平台上如何处理异步任务,涵盖了AsyncTask、Handler、Looper、Loader、IntentService和AlarmManager等关键技术点。这些技术点对于开发响应迅速的Android应用至关...

    Android loopj 文件上传

    代码是基于loopj (Asynchronous Http Client for Android) 的文件上传Demo,loopj 是基于 Apache's HttpClient 的异步http客户端。

    Telemecanique Unity Pro编程的Modicon Premium的Asynchronous serial link的用户手册(2005-英文).zip

    Telemecanique Unity Pro编程的Modicon Premium的Asynchronous serial link的用户手册(2005-英文)zip,Telemecanique Unity Pro编程的Modicon Premium的Asynchronous serial link的用户手册(2005-英文)

    Android开发手册——API函数详解.zip_安卓API

    9. **多线程和异步处理(Multithreading and Asynchronous Processing)**: Android中的Handler、Looper和Runnable是处理后台任务的关键。手册会讲解如何避免主线程阻塞,以及如何使用AsyncTask、IntentService等...

    疯狂的Android讲义光盘源码

    4. **网络通信**:介绍如何使用HttpURLConnection或OkHttp进行网络请求,JSON数据的解析,以及Asynchronous Http Client等第三方库的使用。 5. **多媒体**:涵盖音频、视频的播放与录制,图像加载库如Glide或...

    callback-based Http client on top ..zip

    An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

    tms320f2812官方中文手册datasheet.rar

    提供的"TMS320F2812官方中文手册"详细介绍了该芯片的所有特性和功能,包括硬件结构、编程模型、外设操作以及应用示例。对于初次接触或者深入研究的开发者来说,这是一份非常宝贵的参考资料。 综上所述,TMS320F...

Global site tag (gtag.js) - Google Analytics