`

Android Asynchronous Http Client

 
阅读更多

转自: loopj.com/android-async-http/

github上的地址: https://github.com/loopj/android-async-http

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.

Features

  • Make asynchronous HTTP requests, handle responses in anonymous callbacks
  • HTTP requests happen outside the UI thread
  • Requests use a threadpool to cap concurrent resource usage
  • GET/POST params builder (RequestParams)
  • Multipart file uploads with no additional third party libraries
  • Tiny size overhead to your application, only 19kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Optional built-in response parsing into JSON (JsonHttpResponseHandler)
  • Optional persistent cookie store , saves cookies into your app’s SharedPreferences

Who is Using It?

Heyzap for Android
Social game discovery app with 800,000+ installs

Send me a message on github to let me know if you are using this library in a released android application!

Installation & Basic Usage

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

Import the http package.

 

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

 

Recommended Usage: Make a Static Http Client

In this example, we’ll make a http client class with static accessors to make it easy to communicate with Twitter’s 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:

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 response) {
                // 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 AsyncHttpClient , RequestParams and AsyncHttpResponseHandler Javadocs for more details.

Persistent Cookie Storage with PersistentCookieStore

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.

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.

First, create an instance of 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):

 

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

 

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

To add your own cookies to the store, simply construct a new cookie and call 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.

 

Adding GET/POST Parameters with RequestParams

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

Create empty RequestParams and immediately add some parameters:

 

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

 Create RequestParams for a single parameter:

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

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

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

 See the RequestParams Javadoc for more information.

Uploading Files with RequestParams

The RequestParams class additionally supports multipart file uploads as follows:

Add an InputStream to the RequestParams to upload:

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:

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

 

See the RequestParams Javadoc for more information.

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:

ant package
 

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

Reporting Bugs or Feature Requests

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

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

 

Credits & Contributors

James Smith (http://github.com/loopj )
Creator and Maintainer
Micah Fivecoate (http://github.com/m5 )
Major Contributor, including the original RequestParams
The Droid Fu Project (https://github.com/kaeppler/droid-fu )
Inspiration and code for better http retries
Rafael Sanches (http://blog.rafaelsanches.com )
Original SimpleMultipartEntity code

License

The Android Asynchronous Http Client is released under the Android-friendly Apache License, Version 2.0. Read the full license here:

http://www.apache.org/licenses/LICENSE-2.0

About the Author

I'm James Smith, CTO of heyzap.com . Originally from London, UK I now live in San Francisco.

 

分享到:
评论

相关推荐

    Android Asynchronous Http Client的用法实例

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

    BabySay项目

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

    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 ...

    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的HTTP操作库Volley的基本使用教程

    1.Android Asynchronous Http Client 2.okhttp square开发并且开源的,因为之前用过他们家的picasso,所以对这套满有好感的,只可惜使用方式不太喜欢 3.Volley Volley是Google在2013年Google I/O的时候发布的,到...

    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 ...

    Android UltimateAndroid框架 源码

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

    Android loopj 文件上传

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

    Android代码-Saraba1st论坛的安卓客户端

    网络通信使用 Asynchronous Http Client 实现 图片下载采用 Volley, 图片缓存为 LruCache DiskLruCache 的双重缓存 使用 largeHeap 避免加载大量图片的帖子时出现 OOM 使用 Jsoup分析返回的网络请求 缓存了论坛列表...

    Android SampleNetworking

    来自:http://www.therealjoshua.com/2012/10/android-architecture-structuring-network-calls-part-3/ Android Architecture: Structuring Network Calls, Part 3 October 7th, 2012 · 10 Comments · Android,...

    Android代码-lettuce-core

    asynchronous and reactive usage. Multiple threads may share one connection if they avoid blocking and transactional operations such as BLPOP and MULTI/EXEC. Lettuce is built with netty. Supports ...

    slick-pg_spray-json_2.11-0.6.0-R1.zip

    AndroidAsync.zip,用于Android的异步套接字、HTTP(客户端 服务器)、WebSocket和socket.io库。基于nio,而不是threads.asynchronous socket、http(client server)和android的websocket库。基于nio,而不是线程。

    netty-all-4.1.10.Final.jar netty最新版jar包,直接导入

    Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. Netty is a NIO client server framework which ...

    ICS delphixe10源码版

    ICS V9 is in early development and is planned to support Android. There are no current plans for ICS for iOS. Version Control repository: --------------------------- svn://svn.overbyte.be/ics or ...

    cpprestsdk:C ++ REST SDK是一个Microsoft项目,用于使用现代异步C ++ API设计以本机代码进行基于云的客户端-服务器通信。 该项目旨在帮助C ++开发人员连接到服务并与之交互

    欢迎! C ++ REST SDK是一个Microsoft项目,用于使用现代异步C ... 拥有该库之后,请查看我们的以使用http_client。 它逐步介绍了如何设置项目以使用C ++ Rest SDK并进行基本的Http请求。 要从CMake使用: cmake_min

    taskgroup:将同步和异步任务组合在一起,并在并发,命名和嵌套支持下执行它们

    任务组 将同步和异步任务组合在一起,并在支持并发,命名和嵌套的情况下执行它们。 用法 完整的API文档。 教程和指南。 Web浏览器演示。... 安装: npm install --save taskgroup 导入: import * as pkg from ('...

Global site tag (gtag.js) - Google Analytics