AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler三个类使用方法


(1)AsyncHttpClient
public class AsyncHttpClient extends java.lang.Object
 该类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类 ResponseHandlerInterface的方法处理。
例子:
[java]  view plain copy
  1. AsyncHttpClient client = new AsyncHttpClient();  
  2.  client.get("http://www.google.com"new ResponseHandlerInterface() {  
  3.      @Override  
  4.      public void onSuccess(String response) {  
  5.          System.out.println(response);  
  6.      }  
  7.  });  
(2)RequestParams
public class RequestParams extends java.lang.Object 
用于创建AsyncHttpClient实例中的请求参数(包括字符串或者文件)的集合
例子:
[java]  view plain copy
  1. RequestParams params = new RequestParams();  
  2.  params.put("username""james");  
  3.  params.put("password""123456");  
  4.  params.put("email""my@email.com");  
  5.  params.put("profile_picture"new File("pic.jpg")); // Upload a File  
  6.  params.put("profile_picture2", someInputStream); // Upload an InputStream  
  7.  params.put("profile_picture3"new ByteArrayInputStream(someBytes)); // Upload some bytes  
  8.   
  9.  Map<String, String> map = new HashMap<String, String>();  
  10.  map.put("first_name""James");  
  11.  map.put("last_name""Smith");  
  12.  params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith"  
  13.   
  14.  Set<String> set = new HashSet<String>(); // unordered collection  
  15.  set.add("music");  
  16.  set.add("art");  
  17.  params.put("like", set); // url params: "like=music&like=art"  
  18.   
  19.  List<String> list = new ArrayList<String>(); // Ordered collection  
  20.  list.add("Java");  
  21.  list.add("C");  
  22.  params.put("languages", list); // url params: "languages[]=Java&languages[]=C"  
  23.   
  24.  String[] colors = { "blue""yellow" }; // Ordered collection  
  25.  params.put("colors", colors); // url params: "colors[]=blue&colors[]=yellow"  
  26.   
  27.  List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();  
  28.  Map<String, String> user1 = new HashMap<String, String>();  
  29.  user1.put("age""30");  
  30.  user1.put("gender""male");  
  31.  Map<String, String> user2 = new HashMap<String, String>();  
  32.  user2.put("age""25");  
  33.  user2.put("gender""female");  
  34.  listOfMaps.add(user1);  
  35.  listOfMaps.add(user2);  
  36.  params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"  
  37.   
  38.  AsyncHttpClient client = new AsyncHttpClient();  
  39.  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)方法
例子:
[java]  view plain copy
  1. AsyncHttpClient client = new AsyncHttpClient();  
  2.  client.get("http://www.google.com"new AsyncHttpResponseHandler() {  
  3.      @Override  
  4.      public void onStart() {  
  5.          // Initiated the request  
  6.      }  
  7.   
  8.      @Override  
  9.      public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {  
  10.          // Successfully got a response  
  11.      }  
  12.   
  13.      @Override  
  14.      public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)  
  15.  {  
  16.          // Response failed :(  
  17.      }  
  18.   
  19.      @Override  
  20.      public void onRetry() {  
  21.          // Request was retried  
  22.      }  
  23.   
  24.      @Override  
  25.      public void onProgress(int bytesWritten, int totalSize) {  
  26.          // Progress notification  
  27.      }  
  28.   
  29.      @Override  
  30.      public void onFinish() {  
  31.          // Completed the request (either success or failure)  
  32.      }  
  33.  });  

6.利用PersistentCookieStore持久化存储cookie
PersistentCookieStore类用于实现Apache HttpClient的CookieStore接口,可以自动的将cookie保存到Android设备的SharedPreferences中,如果你打算使用cookie来管理验证会话,这个非常有用,因为用户可以保持登录状态,不管关闭还是重新打开你的app
(1)首先创建 AsyncHttpClient实例对象
[java]  view plain copy
  1. AsyncHttpClient myClient = new AsyncHttpClient();  
(2)将客户端的cookie保存到PersistentCookieStore实例对象,带有activity或者应用程序context的构造方法
[java]  view plain copy
  1. PersistentCookieStore myCookieStore = new PersistentCookieStore(this);  
  2. myClient.setCookieStore(myCookieStore);  
(3)任何从服务器端获取的cookie都会持久化存储到myCookieStore中,添加一个cookie到存储中,只需要构造一个新的cookie对象,并且调用addCookie方法
[java]  view plain copy
  1. BasicClientCookie newCookie = new BasicClientCookie("cookiesare""awesome");  
  2. newCookie.setVersion(1);  
  3. newCookie.setDomain("mydomain.com");  
  4. newCookie.setPath("/");  
  5. myCookieStore.addCookie(newCookie);  

7.利用RequestParams上传文件
类RequestParams支持multipart file 文件上传
(1)在RequestParams 对象中添加InputStream用于上传
[java]  view plain copy
  1. InputStream myInputStream = blah;  
  2. RequestParams params = new RequestParams();  
  3. params.put("secret_passwords", myInputStream, "passwords.txt");  
(2)添加文件对象用于上传
[java]  view plain copy
  1. File myFile = new File("/path/to/file.png");  
  2. RequestParams params = new RequestParams();  
  3. try {  
  4.     params.put("profile_picture", myFile);  
  5. catch(FileNotFoundException e) {}  
(3)添加字节数组用于上传
[java]  view plain copy
  1. byte[] myByteArray = blah;  
  2. RequestParams params = new RequestParams();  
  3. params.put("soundtrack"new ByteArrayInputStream(myByteArray), "she-wolf.mp3");  

8.用BinaryHttpResponseHandler下载二进制数据
[java]  view plain copy
  1. BinaryHttpResponseHandler用于获取二进制数据如图片和其他文件  
  2. AsyncHttpClient client = new AsyncHttpClient();  
  3. String[] allowedContentTypes = new String[] { "image/png""image/jpeg" };  
  4. client.get("http://example.com/file.png"new BinaryHttpResponseHandler(allowedContentTypes) {  
  5.     @Override  
  6.     public void onSuccess(byte[] fileData) {  
  7.         // Do something with the file  
  8.     }  
  9. });  




    
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值