简介
本文所指的AsyncHttpClient是指基于Netty的一个开源项目,该项目基于Java8编写,用于简化HTTP客户端的开发。该项目还支持WebSocket协议。
要使用该AsyncHttpClient,引入以下Maven依赖:
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>LATEST_VERSION</version>
</dependency>
代码示例
配置客户端
AsyncHttpClientConfig cf = new DefaultAsyncHttpClientConfig
.Builder()
// 设置代理服务器
.setProxyServer(new ProxyServer.Builder("127.0.0.1", 8087))
.build();
// 为客户端提供配置项
AsyncHttpClient http = new DefaultAsyncHttpClient(cf);
异步GET请求
ListenableFuture<Response> future =
http.prepareGet( "http://ip:port/path" ).execute( new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted( Response response ) throws Exception {
String resp = response.getResponseBody();
return response;
}
@Override
public void onThrowable( Throwable t ) {
// Something wrong happened.
}
} );
ListenableFuture是java.util.concurrent.Future的子类型,你可以使用Java8并发框架提供的任何特性,例如:
uture.get(); // 阻塞等待处理完毕
// 转换为CompletableFuture
CompletableFuture<Response> promise = future.toCompletableFuture();
promise.exceptionally(t -> { /* 当错误发生时 */ } )
.thenApply(resp -> { /* 处理请求 */ return resp; });
查询参数
http.preparePost( "http://ip:port/path" )
// 添加请求参数
.addQueryParam( "name", alex )
.addQueryParam( "feature", "0" )
.execute()
上传文件
http.preparePost( "http://ip:port/path" )
// 上传多个文件
.addBodyPart( new FilePart( "imageDatas", new ClassPathResource( "alex1.jpg" ).getFile() ) )
.addBodyPart( new FilePart( "imageDatas", new ClassPathResource( "alex2.jpg" ).getFile() ) )
.execute()
发送JSON请求
http.preparePost( "http://192.168.0.89:9090/pems/stpush" )
.addHeader( "Content-Type", "application/json; charset=utf-8" )
.setBody( json.getBytes( "utf-8" ) )
.execute().get();
响应生命周期控制
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String resp = http.prepareGet( "http://www.example.com/" ).execute( new AsyncHandler<String>() {
public void onThrowable( Throwable t ) {
}
public State onBodyPartReceived( HttpResponseBodyPart bodyPart ) throws Exception {
// 接收到一个上传文件后
bytes.write( bodyPart.getBodyPartBytes() );
return State.CONTINUE;
}
public State onStatusReceived( HttpResponseStatus responseStatus ) throws Exception {
// 仅仅获得响应码
int statusCode = responseStatus.getStatusCode();
return State.ABORT;
}
public State onHeadersReceived( HttpHeaders headers ) throws Exception {
// 仅仅接收响应头
return State.ABORT;
}
public String onCompleted() throws Exception {
// 给出此回调的返回值
return bytes.toString( "UTF-8" );
}
} ).get();
WebSocket
WebSocket websocket = http.prepareGet( "http://wsep" )
.execute( new WebSocketUpgradeHandler.Builder().addWebSocketListener(
new WebSocketTextListener() {
@Override
public void onMessage( String message ) {
// 接收到消息时的回调
}
@Override
public void onOpen( WebSocket websocket ) {
// WebSocket打开时的回调
websocket.sendTextMessage( "..." ).sendMessage( "..." );
}
@Override
public void onClose( WebSocket websocket ) {
// 关闭时的回调
}
@Override
public void onError( Throwable t ) {
}
} ).build() ).get();