AsyncHttpClient知识集锦

61 篇文章 0 订阅

简介

本文所指的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();

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值