转载请注明出处: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;

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

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) {
}
} }

AsyncHttpClient 开源框架學習研究的更多相关文章

  1. Asynchttpclient开源框架下载图片和文本,于Volley和Glide开源框架的区别。

    AsyncHttpClient是一款比较流行的Android异步网路加载库,在github上的网址是:https://github.com/loopj/android-async-httpAsyncH ...

  2. android AsyncHttpClient 开源框架的使用

    AsyncHttpClient 1.在很多时候android都需要进行网络的操作,而android自带的HttpClient可以实现,但要进行很多网络连接的时候(如:下载很多图片),就需要线程池来进行 ...

  3. Android 文件上传 使用AsyncHttpClient开源框架

    public void upload(View view) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams reques ...

  4. android开源框架thinkinandroid相关研究

    和命令相关的类有: TAICommand:接口文件,一个命令接口所有命令需要从此实现,还有以下几种方法: TACommandExecutor 命令的实现类,其中含有commands这个成员变量.大部分 ...

  5. 【开源框架EGOTableViewPullRefresh的研究】

    EGOTableViewPullRefresh:点击打开链接https://github.com/enormego/EGOTableViewPullRefresh RootViewController ...

  6. Android 學習之旅!(1)

    就這樣就過去了一年加一個學期,現在是大二第二個學期而且是下半學期了,以前都是無所事事,沒事睡睡覺,打打遊戲就過去了,但是想到家境和以後的路,我還是決心自己找點東西學習下,以後出去還能有一技之長(雖然可 ...

  7. 转】机器学习开源框架Mahout配置与入门研究

    原博文出自于:http://www.ha97.com/5803.html    感谢! PS:机器学习这两年特别火,ATB使劲开百万到几百万年薪招美国牛校的机器学习方向博士,作为一个技术控,也得折腾下 ...

  8. Android开源框架AsyncHttpClient (android-async-http)使用

    android-async-http 开源框架可以使我们轻松地获取网络数据或者向服务器发送数据,最关键的是,它是异步框架,在底层使用线程池处理并发请求,效率很高,使用又特别简单. 以往我们在安卓上做项 ...

  9. 找呀志_通过开源框架引AsyncHttpClient上传文件

    一个.步骤: 1.加入权限(接入网络和可写) 2.获取上传文件的路径和推断是空的 3.如果为空.创建一个异步请求对象 4.创建上传文件路径 5.跑post请求(指定url路径.封装上传參数.新建Asy ...

随机推荐

  1. 利用javascript实现文本的自动输出

    主要利用了setTimeout(),递归和String.substring(); 做出的效果就像是有一个打字员在打字. <!doctype html> <html lang=&quo ...

  2. .Net之美读书系列(一):委托与事件

    开启新的读书之旅,这次读的书为<.Net之美:.Net关键技术深入解析>. 我是选择性阅读的,把一些自己觉得容易忘记的,或者比较重要的知识点记录下来,以便以后能方便呢查阅. 尊重书本原作者 ...

  3. HUD加载动画支持gif

    下载地址 https://pan.baidu.com/s/1c2E7QW4

  4. swift-01-简述swift与OC区别

    swift语言 Swift是Apple在WWDC2014所发布的一门编程语言,用来撰写OS X和iOS应用程序[1].在设计Swift时.就有意和Objective-C共存,Objective-C是A ...

  5. swift-01-利用元组判断字符串出现次数

    //问题的提出:有一个字符串 array = ["1","2","4","4","2"," ...

  6. 洛谷 U3178 zty的冒险之行

    U3178 zty的冒险之行 题目提供者mangoyang 题目背景 "妈咪妈咪轰"随着一声巨响,zty传送到了Aluba国,在那里浴血奋战,饱读兵书,风餐露宿,吃喝嫖赌,终于到了 ...

  7. visual studio vs2010 vs2013 显示详细调试信息方法;vs debug 出错怎么办,你需要的不是答案,是方法。

    显示详细的输出信息: 选项--项目和解决方案--生成并运行--MSBuild项目生成输出详细信息: 这样在输出目录就会显示详细的错误信息,可以自己分析了.

  8. jQuery iframe 自适应高宽度

    Html <iframe id="你的id" src="你要嵌入的页面" scrolling="no" frameborder=&qu ...

  9. 【转】Ext.ajax.request 中的success和failure

    原文链接:Ext.ajax.request 中的success和failure Ajax request对象的success事件表示request过程中没有发生错误,和自己的业务逻辑无关, 如果访问不 ...

  10. e.target与事件委托简例

    target定义: target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素.文档或窗口. 语法: event.target event.target.nodeName  // ...