1.简介
Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-async-http这个库可以大大的简化操作,它是基于Apache’s HttpClient ,所有的请求都是独立在UI主线程之外,通过回调方法处理请求结果,采用android Handlermessage 机制传递信息。
2.特性
(1)采用异步http请求,并通过匿名内部类处理回调结果
(2)http请求独立在UI主线程之外
(3)采用线程池来处理并发请求
(4)采用RequestParams类创建GET/POST参数
(5)不需要第三方包即可支持Multipart file文件上传
(6)大小只有25kb
(7)自动为各种移动电话处理连接断开时请求重连
(8)超快的自动gzip响应解码支持
(9)使用BinaryHttpResponseHandler类下载二进制文件(如图片)
(10) 使用JsonHttpResponseHandler类可以自动将响应结果解析为json格式
(11)持久化cookie存储,可以将cookie保存到你的应用程序的SharedPreferences中
3.使用方法
(1)到官网http://loopj.com/android-async-http/下载最新的android-async-http-1.4.4.jar,然后将此jar包添加进Android应用程序 libs文件夹
(2)通过import com.loopj.android.http.*;引入相关类
(3)创建异步请求
4.建议使用静态的Http Client对象
在下面这个例子,我们创建了静态的http client对象,使其很容易连接到Twitter的API
5. AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler三个类使用方法
(1)AsyncHttpClient
public class AsyncHttpClient extends java.lang.Object
该类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类 ResponseHandlerInterface的方法处理。
例子:
public class RequestParams extends java.lang.Object
用于创建AsyncHttpClient实例中的请求参数(包括字符串或者文件)的集合
例子:
用于拦截和处理由AsyncHttpClient创建的请求。在匿名类AsyncHttpResponseHandler中的重写 onSuccess(int, org.apache.http.Header[], byte[])方法用于处理响应成功的请求。此外,你也可以重写 onFailure(int, org.apache.http.Header[], byte[], Throwable), onStart(), onFinish(), onRetry() 和onProgress(int, int)方法
例子:
6.利用PersistentCookieStore持久化存储cookie
PersistentCookieStore类用于实现Apache HttpClient的CookieStore接口,可以自动的将cookie保存到Android设备的SharedPreferences中,如果你打算使用cookie来管理验证会话,这个非常有用,因为用户可以保持登录状态,不管关闭还是重新打开你的app
(1)首先创建 AsyncHttpClient实例对象
7.利用RequestParams上传文件
类RequestParams支持multipart file 文件上传
(1)在RequestParams 对象中添加InputStream用于上传
8.用BinaryHttpResponseHandler下载二进制数据
Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-async-http这个库可以大大的简化操作,它是基于Apache’s HttpClient ,所有的请求都是独立在UI主线程之外,通过回调方法处理请求结果,采用android Handlermessage 机制传递信息。
2.特性
(1)采用异步http请求,并通过匿名内部类处理回调结果
(2)http请求独立在UI主线程之外
(3)采用线程池来处理并发请求
(4)采用RequestParams类创建GET/POST参数
(5)不需要第三方包即可支持Multipart file文件上传
(6)大小只有25kb
(7)自动为各种移动电话处理连接断开时请求重连
(8)超快的自动gzip响应解码支持
(9)使用BinaryHttpResponseHandler类下载二进制文件(如图片)
(10) 使用JsonHttpResponseHandler类可以自动将响应结果解析为json格式
(11)持久化cookie存储,可以将cookie保存到你的应用程序的SharedPreferences中
3.使用方法
(1)到官网http://loopj.com/android-async-http/下载最新的android-async-http-1.4.4.jar,然后将此jar包添加进Android应用程序 libs文件夹
(2)通过import com.loopj.android.http.*;引入相关类
(3)创建异步请求
- AsyncHttpClientclient=newAsyncHttpClient();
- client.get("http://www.google.com",newAsyncHttpResponseHandler(){
- @Override
- publicvoidonSuccess(Stringresponse){
- System.out.println(response);
- }
- });
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
4.建议使用静态的Http Client对象
在下面这个例子,我们创建了静态的http client对象,使其很容易连接到Twitter的API
- importcom.loopj.android.http.*;
- publicclassTwitterRestClient{
- privatestaticfinalStringBASE_URL="http://api.twitter.com/1/";
- privatestaticAsyncHttpClientclient=newAsyncHttpClient();
- publicstaticvoidget(Stringurl,RequestParamsparams,AsyncHttpResponseHandlerresponseHandler){
- client.get(getAbsoluteUrl(url),params,responseHandler);
- }
- publicstaticvoidpost(Stringurl,RequestParamsparams,AsyncHttpResponseHandlerresponseHandler){
- client.post(getAbsoluteUrl(url),params,responseHandler);
- }
- privatestaticStringgetAbsoluteUrl(StringrelativeUrl){
- returnBASE_URL+relativeUrl;
- }
- }
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;
}
}
然后我们可以很容易的在代码中操作Twitter的API
- importorg.json.*;
- importcom.loopj.android.http.*;
- classTwitterRestClientUsage{
- publicvoidgetPublicTimeline()throwsJSONException{
- TwitterRestClient.get("statuses/public_timeline.json",null,newJsonHttpResponseHandler(){
- @Override
- publicvoidonSuccess(JSONArraytimeline){
- //Pulloutthefirsteventonthepublictimeline
- JSONObjectfirstEvent=timeline.get(0);
- StringtweetText=firstEvent.getString("text");
- //Dosomethingwiththeresponse
- System.out.println(tweetText);
- }
- });
- }
- }
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);
}
});
}
}
5. AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler三个类使用方法
(1)AsyncHttpClient
public class AsyncHttpClient extends java.lang.Object
该类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类 ResponseHandlerInterface的方法处理。
例子:
- AsyncHttpClientclient=newAsyncHttpClient();
- client.get("http://www.google.com",newResponseHandlerInterface(){
- @Override
- publicvoidonSuccess(Stringresponse){
- System.out.println(response);
- }
- });
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new ResponseHandlerInterface() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
(2)RequestParams
public class RequestParams extends java.lang.Object
用于创建AsyncHttpClient实例中的请求参数(包括字符串或者文件)的集合
例子:
- RequestParamsparams=newRequestParams();
- params.put("username","james");
- params.put("password","123456");
- params.put("email","my@email.com");
- params.put("profile_picture",newFile("pic.jpg"));//UploadaFile
- params.put("profile_picture2",someInputStream);//UploadanInputStream
- params.put("profile_picture3",newByteArrayInputStream(someBytes));//Uploadsomebytes
- Map<String,String>map=newHashMap<String,String>();
- map.put("first_name","James");
- map.put("last_name","Smith");
- params.put("user",map);//urlparams:"user[first_name]=James&user[last_name]=Smith"
- Set<String>set=newHashSet<String>();//unorderedcollection
- set.add("music");
- set.add("art");
- params.put("like",set);//urlparams:"like=music&like=art"
- List<String>list=newArrayList<String>();//Orderedcollection
- list.add("Java");
- list.add("C");
- params.put("languages",list);//urlparams:"languages[]=Java&languages[]=C"
- String[]colors={"blue","yellow"};//Orderedcollection
- params.put("colors",colors);//urlparams:"colors[]=blue&colors[]=yellow"
- List<Map<String,String>>listOfMaps=newArrayList<Map<String,String>>();
- Map<String,String>user1=newHashMap<String,String>();
- user1.put("age","30");
- user1.put("gender","male");
- Map<String,String>user2=newHashMap<String,String>();
- user2.put("age","25");
- user2.put("gender","female");
- listOfMaps.add(user1);
- listOfMaps.add(user2);
- params.put("users",listOfMaps);//urlparams:"users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"
- AsyncHttpClientclient=newAsyncHttpClient();
- client.post("http://myendpoint.com",params,responseHandler);
RequestParams params = new RequestParams();
params.put("username", "james");
params.put("password", "123456");
params.put("email", "my@email.com");
params.put("profile_picture", new File("pic.jpg")); // Upload a File
params.put("profile_picture2", someInputStream); // Upload an InputStream
params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
Map<String, String> map = new HashMap<String, String>();
map.put("first_name", "James");
map.put("last_name", "Smith");
params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith"
Set<String> set = new HashSet<String>(); // unordered collection
set.add("music");
set.add("art");
params.put("like", set); // url params: "like=music&like=art"
List<String> list = new ArrayList<String>(); // Ordered collection
list.add("Java");
list.add("C");
params.put("languages", list); // url params: "languages[]=Java&languages[]=C"
String[] colors = { "blue", "yellow" }; // Ordered collection
params.put("colors", colors); // url params: "colors[]=blue&colors[]=yellow"
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> user1 = new HashMap<String, String>();
user1.put("age", "30");
user1.put("gender", "male");
Map<String, String> user2 = new HashMap<String, String>();
user2.put("age", "25");
user2.put("gender", "female");
listOfMaps.add(user1);
listOfMaps.add(user2);
params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://myendpoint.com", params, responseHandler);
(3)public class AsyncHttpResponseHandler extends java.lang.Object implements ResponseHandlerInterface
用于拦截和处理由AsyncHttpClient创建的请求。在匿名类AsyncHttpResponseHandler中的重写 onSuccess(int, org.apache.http.Header[], byte[])方法用于处理响应成功的请求。此外,你也可以重写 onFailure(int, org.apache.http.Header[], byte[], Throwable), onStart(), onFinish(), onRetry() 和onProgress(int, int)方法
例子:
- AsyncHttpClientclient=newAsyncHttpClient();
- client.get("http://www.google.com",newAsyncHttpResponseHandler(){
- @Override
- publicvoidonStart(){
- //Initiatedtherequest
- }
- @Override
- publicvoidonSuccess(intstatusCode,Header[]headers,byte[]responseBody){
- //Successfullygotaresponse
- }
- @Override
- publicvoidonFailure(intstatusCode,Header[]headers,byte[]responseBody,Throwableerror)
- {
- //Responsefailed:(
- }
- @Override
- publicvoidonRetry(){
- //Requestwasretried
- }
- @Override
- publicvoidonProgress(intbytesWritten,inttotalSize){
- //Progressnotification
- }
- @Override
- publicvoidonFinish(){
- //Completedtherequest(eithersuccessorfailure)
- }
- });
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// Initiated the request
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// Successfully got a response
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
{
// Response failed :(
}
@Override
public void onRetry() {
// Request was retried
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
// Progress notification
}
@Override
public void onFinish() {
// Completed the request (either success or failure)
}
});
6.利用PersistentCookieStore持久化存储cookie
PersistentCookieStore类用于实现Apache HttpClient的CookieStore接口,可以自动的将cookie保存到Android设备的SharedPreferences中,如果你打算使用cookie来管理验证会话,这个非常有用,因为用户可以保持登录状态,不管关闭还是重新打开你的app
(1)首先创建 AsyncHttpClient实例对象
- AsyncHttpClientmyClient=newAsyncHttpClient();
AsyncHttpClient myClient = new AsyncHttpClient();
(2)将客户端的cookie保存到PersistentCookieStore实例对象,带有activity或者应用程序context的构造方法
- PersistentCookieStoremyCookieStore=newPersistentCookieStore(this);
- myClient.setCookieStore(myCookieStore);
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
(3)任何从服务器端获取的cookie都会持久化存储到myCookieStore中,添加一个cookie到存储中,只需要构造一个新的cookie对象,并且调用addCookie方法
- BasicClientCookienewCookie=newBasicClientCookie("cookiesare","awesome");
- newCookie.setVersion(1);
- newCookie.setDomain("mydomain.com");
- newCookie.setPath("/");
- myCookieStore.addCookie(newCookie);
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
7.利用RequestParams上传文件
类RequestParams支持multipart file 文件上传
(1)在RequestParams 对象中添加InputStream用于上传
- InputStreammyInputStream=blah;
- RequestParamsparams=newRequestParams();
- params.put("secret_passwords",myInputStream,"passwords.txt");
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
(2)添加文件对象用于上传
- FilemyFile=newFile("/path/to/file.png");
- RequestParamsparams=newRequestParams();
- try{
- params.put("profile_picture",myFile);
- }catch(FileNotFoundExceptione){}
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
(3)添加字节数组用于上传
- byte[]myByteArray=blah;
- RequestParamsparams=newRequestParams();
- params.put("soundtrack",newByteArrayInputStream(myByteArray),"she-wolf.mp3");
byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
8.用BinaryHttpResponseHandler下载二进制数据
- BinaryHttpResponseHandler用于获取二进制数据如图片和其他文件
- AsyncHttpClientclient=newAsyncHttpClient();
- String[]allowedContentTypes=newString[]{"image/png","image/jpeg"};
- client.get("http://example.com/file.png",newBinaryHttpResponseHandler(allowedContentTypes){
- @Override
- publicvoidonSuccess(byte[]fileData){
- //Dosomethingwiththefile
- }
- });
BinaryHttpResponseHandler用于获取二进制数据如图片和其他文件
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
}
});