apache - 是否可以从 HttpClient-5.x 中止 HttpAsynClient 中的 http 请求 [GET、POST 等]?
问题描述
我正在使用 org.apache.hc.client5.http.impl.async.HttpAsyncClients.create() 为我的 HTTP/2 请求创建 org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient。我正在寻找一些功能来从套接字通道读取一些数据后中止请求。
我尝试使用 Future 实例中的 cancel(mayInterruptIfRunning) 方法。但是在中止它之后,我无法获得响应标头和下载的内容。
Future<SimpleHttpResponse> future = null;
CloseableHttpAsyncClient httpClient = null;
try {
httpClient = httpAsyncClientBuilder.build();
httpClient.start();
future = httpClient.execute(target, asyncRequestProducer, SimpleResponseConsumer.create(), null, this.httpClientContext, this);
future.get(10, TimeUnit.SECONDS);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
httpClient.close(CloseMode.GRACEFUL);
}
有没有其他方法可以通过 httpclient-5.x 实现这一点?
提前致谢。
解决方案
当然是。但是您需要实现自己的自定义响应消费者,它可以返回部分消息内容
try (CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault()) {
httpClient.start();
final Future<Void> future = httpClient.execute(
new BasicRequestProducer(Method.GET, new URI("http://httpbin.org/")),
new AbstractCharResponseConsumer<Void>() {
@Override
protected void start(
final HttpResponse response,
final ContentType contentType) throws HttpException, IOException {
System.out.println(response.getCode());
}
@Override
protected int capacityIncrement() {
return Integer.MAX_VALUE;
}
@Override
protected void data(final CharBuffer src, final boolean endOfStream) throws IOException {
}
@Override
protected Void buildResult() throws IOException {
return null;
}
@Override
public void releaseResources() {
}
}, null, null);
try {
future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
future.cancel(true);
}
}
推荐阅读
- javascript - 用 JS .value 替换 JQuery .val()
- javascript - 我如何对特定但重复的元素采取行动
- asp.net-web-api - 处理上传文件与上传文件夹中已存在的文件同名的情况的代码
- javascript - 自谷歌自动播放政策更改以来如何在网站上播放通知声音
- sql - Teradata 存储过程变量
- regex - 如何否定正则表达式?
- typescript - 如何检查字符串文字类型是否包含 TypeScript 中的值?
- c# - 具有 Unity 的实体框架“底层提供程序在打开时失败。”
- string - 我使用 scanf() 将输入作为字符串但使用 cout 输出。为什么我的程序终止了?
- google-cloud-platform - 最佳实践 GCP - GKE | 多种服务