转载请注明出处: http://blog.csdn.net/krislight
OverView:
AsyncHttpClient庫 基於Apache的HttpClient框架,是一個異步的httpClient, 所有的http請求都在子線程中,但是callback執行的線程和創建這個callback的線程是同一個(也即主線程創建的callback那麼執行的時候也是在主線程中)
基本用法:
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); //in MainThread, you can do some ui operation here like progressBar. } @Override public void onFinish() { // no matter success or failed this method is always invoke super.onFinish(); } @Override public void onSuccess(String content) { //success } @Override public void onFailure(Throwable error, String content) { //failed } });
項目中建議定義成靜態工具類:
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; } }
使用的时候:
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); } }); } }
保存Server端發送的Cookie:
AsyncHttpClient myClient = new AsyncHttpClient(); PersistentCookieStore myCookieStore = new PersistentCookieStore(this); myClient.setCookieStore(myCookieStore);
如果想加入自己的Cookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome"); newCookie.setVersion(1); newCookie.setDomain("mydomain.com"); newCookie.setPath("/"); myCookieStore.addCookie(newCookie);
帶參數的Http請求:
可以這樣構造參數:RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data");
也可以構造單個參數:
RequestParams params = new RequestParams("single", "value");
還可以根據Map構造:
HashMap<String, String> paramMap = new HashMap<String, String>(); paramMap.put("key", "value"); RequestParams params = new RequestParams(paramMap);
使用參數上傳文件:
1.傳入InputStream:
InputStream myInputStream = blah; RequestParams params = new RequestParams(); params.put("secret_passwords", myInputStream, "passwords.txt");
2.傳入File:
File myFile = new File("/path/to/file.png"); RequestParams params = new RequestParams(); try { params.put("profile_picture", myFile); } catch(FileNotFoundException e) {}
3.傳入Byte數組:
byte[] myByteArray = blah; RequestParams params = new RequestParams(); params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
下載二進制形式的數據(如圖片,文件等)使用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 } });
基本的http授權驗證:
AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM)); client.get("http://example.com");
使用https安全連接:
AsyncHttpClient client = new AsyncHttpClient(); SSLSocketFactory sf = createSSLSocketFactory(); if(sf != null){ client.setSSLSocketFactory(sf); } HttpProtocolParams.setUseExpectContinue(client.getHttpClient().getParams(), false); return client;
createSSLSocketFactory方法如下:
public static SSLSocketFactory createSSLSocketFactory(){ MySSLSocketFactory sf = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { e.printStackTrace(); } return sf; }
其中MySSLSocketFactory定義
public class MySSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { injectHostname(socket, host); return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } private void injectHostname(Socket socket, String host) { try { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(socket.getInetAddress(), host); } catch (Exception ignored) { } } }
作者:u011176244 发表于2014-2-23 15:04:37 原文链接
阅读:83 评论:0 查看评论