AsyncHttpClient 开源框架學習研究
转载请注明出处: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 开源框架學習研究的更多相关文章
- Asynchttpclient开源框架下载图片和文本,于Volley和Glide开源框架的区别。
AsyncHttpClient是一款比较流行的Android异步网路加载库,在github上的网址是:https://github.com/loopj/android-async-httpAsyncH ...
- android AsyncHttpClient 开源框架的使用
AsyncHttpClient 1.在很多时候android都需要进行网络的操作,而android自带的HttpClient可以实现,但要进行很多网络连接的时候(如:下载很多图片),就需要线程池来进行 ...
- Android 文件上传 使用AsyncHttpClient开源框架
public void upload(View view) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams reques ...
- android开源框架thinkinandroid相关研究
和命令相关的类有: TAICommand:接口文件,一个命令接口所有命令需要从此实现,还有以下几种方法: TACommandExecutor 命令的实现类,其中含有commands这个成员变量.大部分 ...
- 【开源框架EGOTableViewPullRefresh的研究】
EGOTableViewPullRefresh:点击打开链接https://github.com/enormego/EGOTableViewPullRefresh RootViewController ...
- Android 學習之旅!(1)
就這樣就過去了一年加一個學期,現在是大二第二個學期而且是下半學期了,以前都是無所事事,沒事睡睡覺,打打遊戲就過去了,但是想到家境和以後的路,我還是決心自己找點東西學習下,以後出去還能有一技之長(雖然可 ...
- 转】机器学习开源框架Mahout配置与入门研究
原博文出自于:http://www.ha97.com/5803.html 感谢! PS:机器学习这两年特别火,ATB使劲开百万到几百万年薪招美国牛校的机器学习方向博士,作为一个技术控,也得折腾下 ...
- Android开源框架AsyncHttpClient (android-async-http)使用
android-async-http 开源框架可以使我们轻松地获取网络数据或者向服务器发送数据,最关键的是,它是异步框架,在底层使用线程池处理并发请求,效率很高,使用又特别简单. 以往我们在安卓上做项 ...
- 找呀志_通过开源框架引AsyncHttpClient上传文件
一个.步骤: 1.加入权限(接入网络和可写) 2.获取上传文件的路径和推断是空的 3.如果为空.创建一个异步请求对象 4.创建上传文件路径 5.跑post请求(指定url路径.封装上传參数.新建Asy ...
随机推荐
- 高级Magento模型 EAV
我们讲过Magento有两种模型,简单模型和EAV(Entity Attribute Value)模型.上一章我们讲过所有的Magento模型都是继承自Mage_Core_Model_Abstract ...
- MySQL之DML语句(insert update delete)
DML主要针对数据库表对象的数据而言的,一般DML完成: 插入新数据 修改已添加的数据 删除不需要的数据 1.insert into插入语句 //主键自增可以不插入,所以用null代替 ); //指定 ...
- Dom操作--全选反选
我们经常会在网站上遇到一些多选的情况,下面我就来说说使用Dom写全选反选的思路. 全选思路:首先,我们来分析一下知道,当我们点击"全选"复选框的时候,所有的复选框应该都被选中,那我 ...
- ACM——简单排序
简单选择排序 时间限制(普通/Java):1000MS/3000MS 运行内存限制:65536KByte总提交:836 测试通过:259 描述 给定输入排序元素 ...
- AppDelegate 方法详解
iOS 程序启动时总会调用application:didFinishLaunchingWithOptions:,其中第二个参数launchOptions为NSDictionary类型的对象,里面存储有 ...
- java I/O技术
一.流的分类 Java的流类大部分都是由InputStream.OutputStream.Reader和Writer这四个抽象类派生出来的 (1)按数据流向 输入流(InputStream类和Read ...
- 国庆第七日(2014年10月7日17:55:56),随手记,一些关注的OSC软件,花生壳
(1)最难过的是今天. (2)随手记:001.002. (3)htmlunit.joda-time.date4j.jdao.BeanGenerator.JavaScript秘密花园(开源图书) OS ...
- UVA 10795 A Different Task(汉诺塔 递归))
A Different Task The (Three peg) Tower of Hanoi problem is a popular one in computer science. Briefl ...
- MongoDB源码分析——mongod程序源码入口分析
Edit 说明:第一次写笔记,之前都是看别人写的,觉得很简单,开始写了之后才发现真的很难,不知道该怎么分析,这篇文章也参考了很多前辈对MongoDB源码的分析,也有一些自己的理解,后续将会继续分析其他 ...
- (转)C++设计模式——观察者模式
转自:http://www.jellythink.com/archives/359 前言 之前做了一个性能测试的项目,就是需要对现在的产品进行性能测试,获得测试数据,然后书写测试报告,并提出合理化的改 ...