AsyncHttpClient使用教程(一)(翻译自Github)
来源:互联网 发布:js实现拖拽工作流配置 编辑:程序博客网 时间:2024/06/01 10:22
最近公司启动了一个新项目,由于之前的老项目代码混论、沉重,导致本次下定决心整治项目架构和代码质量。使用了很多新的第三方库,今天先看了一下网络通信库,AsyncHttpClient。一下内容大部分翻译自github,由于本人英文水平有限,难免有不妥的地方,请大家指正。
AsyncHttpClient库可以让一个java应用便捷的执行HTTP请求并异步的响应HTTP的应答。而且这个库还支持WebSocket协议。其使用非常方便,下面我们来看一下他的使用方法。
首先,你要在你的项目里引入AsyncHttpClient,如果你使用maven来构建,可以很简单的引入:
<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.9.0</version>
</dependency>
你也可以使用引入jar包的方式来使用它。
使用方法也是很简单的,下面是示例代码,仅仅三行而已:
importcom.ning.http.client.*;
importjava.util.concurrent.Future;
AsyncHttpClientasyncHttpClient = new AsyncHttpClient();
Future<Response>f = asyncHttpClient.prepareGet("http://www.ning.com/").execute();
Responser = f.get();
以上是最简单的一种使用方法,注意在这个例子中所有的应答内容都必须预先读到内存中,即使你使用的是getResponseBodyAsStream()方法来获取结果。
你可以在handler里对应答作出操作,这尤其在andorid系统显得很重要。以下是示例代码:
importcom.ning.http.client.*;
importjava.util.concurrent.Future;
AsyncHttpClientasyncHttpClient = new AsyncHttpClient();
asyncHttpClient.prepareGet("http://www.ning.com/").execute(newAsyncCompletionHandler<Response>(){
@Override
public Response onCompleted(Responseresponse) throws Exception{
// Do something with the Response
// ...
return response;
}
@Override
public void onThrowable(Throwable t){
// Something wrong happened.
}
});
(这种方式同样会预先把response读取到内存中。)
你还可以混合使用以上两种方式,这样可以只读取整个response内容的一部分。以下是示例代码:
importcom.ning.http.client.*;
importjava.util.concurrent.Future;
AsyncHttpClientasyncHttpClient = new AsyncHttpClient();
Future<Integer>f = asyncHttpClient.prepareGet("http://www.ning.com/").execute(
new AsyncCompletionHandler<Integer>(){
@Override
public Integer onCompleted(Responseresponse) throws Exception{
// Do something with the Response
return response.getStatusCode();
}
@Override
public void onThrowable(Throwable t){
// Something wrong happened.
}
});
intstatusCode = f.get();
这种情况下我们就只读取了一个状态码。
当你预期获取的内容比较大时,只要应答已经可读,你就可以一段一段的读取它,而不是把整个内容都先读到内存中。
该库还有一个大的优点就是你可以完全控制整个response的生命周期,因此你可以决定在任意时刻停止接受服务器的返回。示例代码如下:
import com.ning.http.client.*;
importjava.util.concurrent.Future;
AsyncHttpClientc = new AsyncHttpClient();
Future<String>f = c.prepareGet("http://www.ning.com/").execute(newAsyncHandler<String>() {
private ByteArrayOutputStream bytes = newByteArrayOutputStream();
@Override
public STATEonStatusReceived(HttpResponseStatus status) throws Exception {
int statusCode = status.getStatusCode();
// The Status have been read
// If you don't want to read theheaders,body or stop processing the response
if (statusCode >= 500) {
return STATE.ABORT;
}
}
@Override
public STATEonHeadersReceived(HttpResponseHeaders h) throws Exception {
Headers headers = h.getHeaders();
// The headers have been read
// If you don't want to read the body,or stop processing the response
return STATE.ABORT;
}
@Override
public STATEonBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
bytes.write(bodyPart.getBodyPartBytes());
return STATE.CONTINUE;
}
@Override
public String onCompleted() throwsException {
// Will be invoked once the responsehas been fully read or a ResponseComplete exception
// has been thrown.
// NOTE: should probably useContent-Encoding from headers
return bytes.toString("UTF-8");
}
@Override
public void onThrowable(Throwable t) {
}
});
StringbodyResponse = f.get();
通过代码可以看出,我们可以控制读取的内容,比如只读取状态码,读取到header信息为止,读取完body为止,完全读取成功等等。
我们可以通过AsynHttpClientConfig类为你的应用程序设置代理服务器和端口。示例代码如下:
AsyncHttpClientConfigcf = new AsyncHttpClientConfig.Builder()
S.setProxyServer(newProxyServer("127.0.0.1", 38080)).build();
AsyncHttpClientc = new AsyncHttpClient(cf);
先写到这里,要下班了。下周把剩余的补上。^_^
- AsyncHttpClient使用教程(一)(翻译自Github)
- Github使用教程(一)------ 初识Github
- Github使用教程(一)
- GitHub使用教程(一)
- Grunt 入门教程一:开始使用Grunt(翻译自官方教程)
- Grunt 入门教程一:开始使用Grunt(翻译自官方教程)
- GitHub for Windows使用教程(一)
- GitHub for Windows使用教程(一)
- Github客户端安装使用教程(一)
- Android AsyncHttpClient https使用教程
- GitHub教程(一)
- Github使用教程(一)--搭建Github环境
- 如何使用github?github简单使用教程(转自http://blog.sina.com.cn/dashanliu)
- GitHub for Windows使用教程(一)安装配置
- object_detection“使用教程”翻译(一):configuring_jobs.md
- Nim教程翻译(一)
- GitHub使用教程详解(上)——官网操作指南[翻译]
- Git使用教程(一)--搭建Github环境
- SMALI 语法学习
- 比memcpy更快的内存拷贝【转】
- 数据结构C++版第7章节笔记
- 【公告】博客数据异常已全部恢复
- ContentProvider和Uri详解
- AsyncHttpClient使用教程(一)(翻译自Github)
- 黑马程序员 -- Java基础学习(5)
- Java 异常
- 关于11月28日CSDN遭受网络攻击的情况说明
- 千里之行始于足下——编译器助手(binutils与elf文件)
- 用docker搭建spark集群
- wujiepei_520霸榜可否?
- 这个不用了,用另一个帐号,有更多我的分享
- 愚者的亡途