关于android-async-http

关于该框架介绍:

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

Overview

An asynchronous callback-based Http client for Android built on top of Apache’sHttpClient libraries.All requests are made outside of your app’s main UI thread, but any callbacklogic will be executed on the same thread as the callback was created usingAndroid’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 25kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Binary file (images etc) downloading with BinaryHttpResponseHandler
  • Built-in response parsing into JSON with JsonHttpResponseHandler
  • Persistent cookie store, saves cookies into your app’s SharedPreferences

Used in Production By Top Apps and Developers

Instagram
Instagram is the #1 photo app on android, with over 10million users
Pinterest
Popular online pinboard. Organize and share things you love.
Frontline Commando (Glu Games)
#1 first person shooting game on Android, by Glu Games.
Heyzap
Social game discovery app with millions of users
Pose
Pose is the #1 fashion app for sharing and discovering new styles
Thousands more apps…
Async HTTP is used in production by thousands of top apps.

Installation & Basic Usage

Download the latest .jar file from github and place it in your Android app’slibs/ 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);
    }
});

In this example, we’ll make a http client class with static accessors to makeit 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 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);
            }
        });
    }
}

Check out theAsyncHttpClient,RequestParams andAsyncHttpResponseHandlerJavadocs for more details.

This library also includes a PersistentCookieStore which is an implementationof the Apache HttpClient CookieStore interface that automatically savescookies to SharedPreferences storage on the Android device.

This is extremely useful if you want to use cookies to manage authenticationsessions, since the user will remain logged in even after closing andre-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 ofPersistentCookieStore, 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 cookiestore.

To add your own cookies to the store, simply construct a new cookie andcall addCookie:

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

See the PersistentCookieStore Javadocfor more information.

Adding GET/POST Parameters with RequestParams

The RequestParams class is used to add optional GET or POST parameters toyour 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 Javadocfor more information.

Uploading Files with RequestParams

The RequestParams class additionally supports multipart file uploads asfollows:

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 Javadocfor more information.

Downloading Binary Data with BinaryHttpResponseHandler

The BinaryHttpResponseHandler class can be used to fetch binary data suchas images and other files. For example:

AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) {
    @Override
    public void onSuccess(byte[] fileData) {
        // Do something with the file
    }
});

See the BinaryHttpResponseHandler Javadocfor more information.

Adding HTTP Basic Auth credentials

Some requests may need username/password credentials when dealing with API services that use HTTP Basic Access Authentication requests. You can use the method setBasicAuth() to provide your credentials.

Set username/password for any host and realm for a particular request. By default the Authentication Scope is for any host, port and realm.

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

You can also provide a more specific Authentication Scope (recommended)

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

See the RequestParams Javadocfor 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 thisproject here:

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

Credits & Contributors

James Smith ( http://github.com/loopj)
Creator and Maintainer
Marek Sebera ( http://github.com/smarek)
Maintainer since 1.4.4 release
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
Anthony Persaud ( http://github.com/apersaud)
Added support for HTTP Basic Authentication requests.
Linden Darling ( http://github.com/coreform)
Added support for binary/image responses

License

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

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

About the Author

James Smith, British entrepreneur and developer based in San Francisco.

I'm the co-founder of Bugsnag with Simon Maynard, and from 2009 to 2012 I led up the product team as CTO of Heyzap.


以下这段摘自:

http://www.2cto.com/kf/201304/204575.html


在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Instagram和Pinterest的Android版就是用的这个网络请求库。这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。

其主要特征如下:
处理异步Http请求,并通过匿名内部类处理回调结果
Http请求均位于非UI线程,不会阻塞UI操作
通过线程池处理并发请求
处理文件上传、 下载
响应结果自动打包JSON格式
自动处理连接断开时请求重连
使用android-async-http也非常简单,到官网http://loopj.com/android-async-http/下载依赖jar包,导入工程中libs文件夹下并添加到工程路径即可。通过下面的代码来创建一个异步请求:
[java]  
AsyncHttpClient client = new AsyncHttpClient();  
                client.get("http://www.baidu.com", new AsyncHttpResponseHandler() {  
                      
                    @Override  
                    public void onSuccess(String response) {  
                        System.out.println(response);  
                        textView.setText(response);  
                    }  
                      
                    @Override  
                    public void onStart() {  
                        super.onStart();  
                        System.out.println("onStart");  
                    }  
                      
                    @Override  
                    public void onFinish() {  
                        super.onFinish();  
                        System.out.println("onFinish");  
                    }  
                      
                }  
 
 
通过Get请求指定的URL并通过回调函数处理请求结果,同时,请求方式还支持POST和PUT,请求的同时还支持参数传递,下面看看如何通过JSON字符串作为参数访问服务器:
[java] 
try {  
                    JSONObject jsonObject = new JSONObject();  
                    jsonObject.put("username", "ryantang");  
                    StringEntity stringEntity = new StringEntity(jsonObject.toString());  
                    client.post(MainActivity.this, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){  
  
                        @Override  
                        public void onSuccess(JSONObject jsonObject) {  
                            super.onSuccess(jsonObject);  
                              
                        }  
                          
                    });  
                } catch (JSONException e) {  
                    e.printStackTrace();  
                } catch (UnsupportedEncodingException e) {  
                    e.printStackTrace();  
                }  
 
官方推荐的使用方法,使用一个静态的请求对象,我们来看看官方例举的一个访问Twitter的API的例子:
使用方法:
 
由于涉及网络请求,最后别忘了添加权限:
[ html]  
<uses-permission android:name="android.permission.INTERNET" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值