AsyncHttpClient

AsyncHttpClient庫 基於Apache的HttpClient框架,是一個異步的httpClient, 所有的http請求都在子線程中,但是callback執行的線程和創建這個callback的線程是同一個(也即主線程創建的callback那麼執行的時候也是在主線程中)

基本用法:  

[java] view plaincopy

  1. AsyncHttpClient client = new AsyncHttpClient();  

  2.     client.get("http://www.google.com"new AsyncHttpResponseHandler() {  

  3.               @Override  

  4.             public void onStart() {  

  5.                 super.onStart();  

  6.                     //in MainThread, you can do some ui operation here like progressBar.    

  7.             }  

  8.               

  9.             @Override  

  10.             public void onFinish() {  

  11.                     // no matter success or failed this method is always invoke  

  12.                 super.onFinish();  

  13.             }  

  14.               

  15.             @Override  

  16.             public void onSuccess(String content) {  

  17.                    //success  

  18.             }  

  19.               

  20.             @Override  

  21.             public void onFailure(Throwable error, String content) {  

  22.                   //failed  

  23.             }     

  24. });  


項目中建議定義成靜態工具類:                   

[java] view plaincopy

  1. public class TwitterRestClient {  

  2.           private static final String BASE_URL = "http://api.twitter.com/1/";  

  3.           private static AsyncHttpClient client = new AsyncHttpClient();  

  4.           public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {  

  5.               client.get(getAbsoluteUrl(url), params, responseHandler);  

  6.           }  

  7.           public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {  

  8.               client.post(getAbsoluteUrl(url), params, responseHandler);  

  9.           }  

  10.           private static String getAbsoluteUrl(String relativeUrl) {  

  11.               return BASE_URL + relativeUrl;  

  12.           }  

  13.         }  


使用的时候:           

[java] view plaincopy

  1. class TwitterRestClientUsage {  

  2.         public void getPublicTimeline() throws JSONException {  

  3.             TwitterRestClient.get("statuses/public_timeline.json"nullnew JsonHttpResponseHandler() {  

  4.                 @Override  

  5.                 public void onSuccess(JSONArray timeline) {  

  6.                     // Pull out the first event on the public timeline  

  7.                     JSONObject firstEvent = timeline.get(0);  

  8.                     String tweetText = firstEvent.getString("text");  

  9.   

  10.                     // Do something with the response  

  11.                     System.out.println(tweetText);  

  12.                 }  

  13.             });  

  14.         }  

  15.     }  


保存Server端發送的Cookie                     

[java] view plaincopy

  1. AsyncHttpClient myClient = new AsyncHttpClient();  

  2.     PersistentCookieStore myCookieStore = new PersistentCookieStore(this);  

  3.     myClient.setCookieStore(myCookieStore);  


如果想加入自己的Cookie:

 

[java] view plaincopy

  1.     BasicClientCookie newCookie = new BasicClientCookie("cookiesare""awesome");  

  2. newCookie.setVersion(1);  

  3. newCookie.setDomain("mydomain.com");  

  4. newCookie.setPath("/");  

  5. myCookieStore.addCookie(newCookie);  


帶參數的Http請求:

可以這樣構造參數:

[java] view plaincopy

  1. RequestParams params = new RequestParams();  

  2.     params.put("key""value");  

  3.     params.put("more""data");  


也可以構造單個參數:

[java] view plaincopy

  1. RequestParams params = new RequestParams("single""value");  


 還可以根據Map構造:

[java] view plaincopy

  1. HashMap<String, String> paramMap = new HashMap<String, String>();  

  2. paramMap.put("key""value");  

  3. RequestParams params = new RequestParams(paramMap);  


使用參數上傳文件:

1.傳入InputStream:

 

[java] view plaincopy

  1.  InputStream myInputStream = blah;  

  2. RequestParams params = new RequestParams();  

  3. params.put("secret_passwords", myInputStream, "passwords.txt");  


2.傳入File:

[java] view plaincopy

  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.傳入Byte數組:

[java] view plaincopy

  1. byte[] myByteArray = blah;  

  2. RequestParams params = new RequestParams();  

  3. params.put("soundtrack"new ByteArrayInputStream(myByteArray), "she-wolf.mp3");  


下載二進制形式的數據(如圖片,文件等)使用BinaryHttpResponseHandler:

[java] view plaincopy

  1.  AsyncHttpClient client = new AsyncHttpClient();  

  2. String[] allowedContentTypes = new String[] { "image/png""image/jpeg" };  

  3. client.get("http://example.com/file.png"new BinaryHttpResponseHandler(allowedContentTypes) {  

  4.         @Override  

  5.         public void onSuccess(byte[] fileData) {  

  6.             // Do something with the file  

  7.         }  

  8.     });  


基本的http授權驗證:

[java] view plaincopy

  1. AsyncHttpClient client = new AsyncHttpClient();  

  2.     client.setBasicAuth("username","password"new AuthScope("example.com"80, AuthScope.ANY_REALM));  

  3.     client.get("http://example.com");  


使用https安全連接:

[java] view plaincopy

  1. AsyncHttpClient client = new AsyncHttpClient();  

  2.     SSLSocketFactory sf = createSSLSocketFactory();  

  3.          if(sf != null){  

  4.             client.setSSLSocketFactory(sf);  

  5.          }  

  6.         HttpProtocolParams.setUseExpectContinue(client.getHttpClient().getParams(), false);  

  7.         return client;  


转载请注明出处: http://blog.csdn.net/krislight

createSSLSocketFactory方法如下:

[java] view plaincopy

  1. public static SSLSocketFactory createSSLSocketFactory(){  

  2.         MySSLSocketFactory sf = null;  

  3.         try {  

  4.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  

  5.             trustStore.load(nullnull);  

  6.             sf = new MySSLSocketFactory(trustStore);  

  7.             sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  

  8.         } catch (Exception e) {  

  9.             e.printStackTrace();  

  10.         }  

  11.         return sf;  

  12.     }  


其中MySSLSocketFactory定義

[java] view plaincopy

  1. public class MySSLSocketFactory extends SSLSocketFactory {  

  2.     SSLContext sslContext = SSLContext.getInstance("TLS");  

  3.   

  4.     public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {  

  5.         super(truststore);  

  6.   

  7.         TrustManager tm = new X509TrustManager() {  

  8.             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  

  9.             }  

  10.   

  11.             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  

  12.             }  

  13.   

  14.             public X509Certificate[] getAcceptedIssuers() {  

  15.                 return null;  

  16.             }  

  17.         };  

  18.   

  19.         sslContext.init(nullnew TrustManager[] { tm }, null);  

  20.     }  

  21.   

  22.     @Override  

  23.     public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {  

  24.         injectHostname(socket, host);  

  25.         return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);  

  26.     }  

  27.   

  28.     @Override  

  29.     public Socket createSocket() throws IOException {  

  30.         return sslContext.getSocketFactory().createSocket();  

  31.     }  

  32.       

  33.     private void injectHostname(Socket socket, String host) {  

  34.         try {  

  35.             Field field = InetAddress.class.getDeclaredField("hostName");  

  36.             field.setAccessible(true);  

  37.             field.set(socket.getInetAddress(), host);  

  38.         } catch (Exception ignored) {  

  39.         }  

  40.     }  


你可能感兴趣的:(AsyncHttpClient)