AsyncHttpClient庫 基於Apache的HttpClient框架,是一個異步的httpClient, 全部的http請求都在子線程中,可是callback執行的線程和創建這個callback的線程是同一個(也即主線程創建的callback那麼執行的時候也是在主線程中)java
基本用法: json
[java] view plaincopyapi
AsyncHttpClient client = new AsyncHttpClient(); 安全
client.get("http://www.google.com", new AsyncHttpResponseHandler() { cookie
@Override 框架
public void onStart() { dom
super.onStart(); socket
//in MainThread, you can do some ui operation here like progressBar. ide
} 工具
@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
}
});
項目中建議定義成靜態工具類:
[java] view plaincopy
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;
}
}
使用的時候:
[java] view plaincopy
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:
[java] view plaincopy
AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
若是想加入本身的Cookie:
[java] view plaincopy
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
帶參數的Http請求:
能夠這樣構造參數:
[java] view plaincopy
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
也能夠構造單個參數:
[java] view plaincopy
RequestParams params = new RequestParams("single", "value");
還能夠根據Map構造:
[java] view plaincopy
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
使用參數上傳文件:
1.傳入InputStream:
[java] view plaincopy
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
2.傳入File:
[java] view plaincopy
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
3.傳入Byte數組:
[java] view plaincopy
byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
下載二進制形式的數據(如圖片,文件等)使用BinaryHttpResponseHandler:
[java] view plaincopy
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授權驗證:
[java] view plaincopy
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("http://example.com");
使用https安全連接:
[java] view plaincopy
AsyncHttpClient client = new AsyncHttpClient();
SSLSocketFactory sf = createSSLSocketFactory();
if(sf != null){
client.setSSLSocketFactory(sf);
}
HttpProtocolParams.setUseExpectContinue(client.getHttpClient().getParams(), false);
return client;
轉載請註明出處: http://blog.csdn.net/krislight
createSSLSocketFactory方法以下:
[java] view plaincopy
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定義
[java] view plaincopy
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) {
}
}