基本使用
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
httpClient.start();
SimpleHttpRequest request = SimpleHttpRequests.get("http://httpbin.org/get");
Future<SimpleHttpResponse> future = httpClient.execute(request, null);
try {
SimpleHttpResponse response = future.get();
log.info("{}\t\t{}", response.getCode(), response.getBodyText());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
使用回调函数
Future<SimpleHttpResponse> future = httpClient.execute(request, new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(SimpleHttpResponse response) {
log.error("{} -> {}", request.getRequestUri(), response.getCode());
}
@Override
public void failed(Exception e) {
log.error("{} -> {}", request.getRequestUri(), e);
}
@Override
public void cancelled() {
log.info("{} cancelled", request.getRequestUri());
}
});
生产者-消费者 模式
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
httpClient.start();
//生产者
AsyncRequestProducer producer = AsyncRequestBuilder.get("http://httpbin.org/get").build();
//消费者
AbstractCharResponseConsumer<CloseableHttpResponse> consumer = new AbstractCharResponseConsumer<>() {
CloseableHttpResponse response;
@Override
public void releaseResources() {
}
@Override
protected int capacityIncrement() {
return Integer.MAX_VALUE;
}
@Override
protected void data(CharBuffer charBuffer, boolean b) throws IOException {
log.info("-> {}", charBuffer);
}
@Override
protected void start(HttpResponse httpResponse, ContentType contentType) throws HttpException, IOException {
this.response = (CloseableHttpResponse) httpResponse;
}
@Override
protected CloseableHttpResponse buildResult() throws IOException {
return response;
}
};
httpClient.execute(producer, consumer, new FutureCallback<CloseableHttpResponse>() {
@Override
public void completed(CloseableHttpResponse response) {
log.info("-> {}", response.getCode());
}
@Override
public void failed(Exception e) {
log.info("-> {}", e);
}
@Override
public void cancelled() {
log.info("-> cancelled");
}
});