转载请注明出处: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入门(7)

    一.什么是函数 函数:把完成特定功能的代码放到一个函数里,直接调用这个函数,就省去重复输入大量代码的麻烦 函数的作用:写一次代码,然后反复地重用这个代码 Eg: 求多组数的和,不使用函数 { var ...

  2. ACM——A + B Problem (1)

    A + B Problem (1) 时间限制(普通/Java):1000MS/3000MS          运行内存限制:65536KByte总提交:5907            测试通过:151 ...

  3. Android 讯飞语音之语音合成(在线有声朗读)

    原文:http://www.cnblogs.com/scetopcsa/p/3845427.html 在线语音合成的使用方法: 首先下载相关的sdk,这个网址里有多种版本,我选择的Android. h ...

  4. EasyUI兼容IE问题

    上网搜了下,发现说明白的解决方案不多,于是记录了一下: 根本原因是JQuery的版本造成IE8及以下兼容的问题,(由于EasyUI是基于JQuery框架的,而JQuery貌似从2013年为了简洁代码, ...

  5. FastFrameWork 快速开发框架

    前言 FastFrameWork 快速开发框架是一款基于敏捷并行开发思想和Microsoft .Net构件(插件)开发技术而构建的一个快速开发应用平台.用于帮助中小型软件企业建立一条适合市场快速变化的 ...

  6. PHP mysql_real_escape_string() 函数防SQL注入

    PHP MySQL 函数 定义和用法 mysql_real_escape_string() 函数转义 SQL 语句中使用的字符串中的特殊字符. 下列字符受影响: \x00 \n \r \ ' &quo ...

  7. JavaScript高级程序设计(一):JavaScript简介

    一.JavaScript实现 1.一个完整的JavaScript包含三个部分组成: 1)ECMAScript 核心 2)DOM文档对象模型 3)BOM浏览器对象模型 2.文档对象模型(DOM) 文档对 ...

  8. Ios 给imageview 添加手势没有反应

    道理差不多,简单写写,就是给UIImage所在的UIImageView添加个单击的手势,让用户点击图片时有响应的响应. 有人用个透明的UIButton,感觉有时候不方便.   - (void)view ...

  9. C# 简单的图像边缘提取

    博主做的很简单,大家看一看就好了...... 用到的算法是robert算子,这是一种比较简单的算法: f(x,y)=sqrt((g(x,y)-g(x+1,y+1))^2+(g(x+1,y)-g(x,y ...

  10. requirejs实践二 加载其它JavaScript与运行

    上一篇中介绍了requirejs加载JavaScript文件,在这一篇中介绍加载JavaScript后执行代码 这次是test2.html文件, <!DOCTYPE html> <h ...