转载请注明出处: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. asp.net Ajax Post 请求一般处理程序

    其实很早就开通博客园了,一直想写些有价值的东西,供自己以后查阅的同时,也可以帮助别人遇到此类问题时能有一个好的解决方法.但是由于各种原因, 就没有实施我的想法.今天突然很想写下一篇文章,不知道我的第一 ...

  2. android测试分析1

    Android测试框架,开发环境中集成的一部分,提供一个架构和强有力的工具 可以帮助测试你的应用从单元到框架的每个方面. 测试框架有这些主要特征: 1.Android测试组件基于Junit.你可以使用 ...

  3. js获得文件根目录

    function getRootPath(){ //获取当前网址,如: http://localhost:8083/proj/meun.jsp var curWwwPath = window.docu ...

  4. EF中使用语句 或存储过程 查询(转)

    EF中使用语句 或存储过程 查询 1.无参数查询 var model = db.Database.SqlQuery("select* from UserInfoes ").ToLi ...

  5. 关于Debug下的Log打印问题

    在项目中为了调试经常会用到Log打印,比如打印当前方法__func__, 对象,地址等等,所以项目最后每次运行调试控制台满满的都是打印日志,到release发布的时候,显然不太合适,这里其实可以用一个 ...

  6. TreeListView的用法

    public void ProductBind() { tlvProduct.Items.Clear(); List<ProductInfo> list = ppbll.GetProduc ...

  7. [002] The Perks of Being a Wallflower - 读后记

    The Perks of Being a Wallflower 今天(2015年10月30日 18:26:17)读完"The Perks of Being a Wallflower" ...

  8. 国庆第三天2014年10月3日10:21:39,Nutz,WebCollector,jsoup

    (1)做得好,做得快,只能选择一样. (2)时间过得很快,你没法在假期的一天里完成更多的计划.假期全部由自己支配,相对长一点的睡眠,新加入的娱乐(视频或者游戏),你不比在工作中更有效率. (3)每天练 ...

  9. 暑假集训(2)第一弹 -----Is It A Tree?(Poj308)

    A - Is It A Tree? Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:10000KB  ...

  10. cocos2d-x v3.0的window平台搭建和编译成andriod程序

    首先添加这个地址到系统环境变量,path 然后打开CMD,输入如下语句 现在就可以创建一个新项目了 这样一个空的cocos2d-x v3.0的项目就创建好了 接下来编译andriod程序 先在系统环境 ...