【问题标题】:How do you consume http response content asynchronously with Apache's HTTP async client?您如何使用 Apache 的 HTTP 异步客户端异步使用 http 响应内容?
【发布时间】:2016-10-27 13:29:31
【问题描述】:

我是 Java NIO 的新手。我用它来发出 HTTP Get 请求。请求正确执行,但我无法弄清楚如何获取响应的内容。

例如,

CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
httpClient.start();
url = buildUrl(); //builds the url for the GET request
BasicAsyncResponseConsumer consumer = new BasicAsyncResponseConsumer();
 Future<HttpResponse> future = httpClient.execute(HttpAsyncMethods.createGet(url), consumer, null)

现在如何获取响应的内容?在打印未来时,我得到以下信息:

HTTP/1.1 200 OK [Content-Type: application/json, Date: Fri, 24 Jun 2016 20:21:47 GMT, Content-Length: 903, Connection: keep-alive] [Content-Length: 903,Chunked: false]

我的响应(在浏览器上)是 903 个字符,所以我知道它正确地发出请求。但是,如何打印出结果的 json 内容?

【问题讨论】:

  • 您使用的是哪个库?你似乎没有使用 NIO。
  • 我一直在用蔚来?
  • 您之前可能使用过 NIO,但您在此处提到的代码中没有。提示:你在使用java.nio 包中的任何类吗?

标签: java apache-httpasyncclient


【解决方案1】:

有几种方法可以解决这个问题。

一,在execute返回的Future上调用get(),阻塞直到准备好结果。一旦结果准备好,get() 将返回HttpResponse 对象,您可以使用该对象来检索带有getEntity 的内容。 HttpEntity 有一个 InputStream。阅读您认为合适的内容。

第二,提供比BasicAsyncResponseConsumer 更智能的HttpAsyncResponseConsumer 实现,它读取(并关闭)HttpResponseHttpEntity 并生成一个可以被FutureCallback 使用的值,该值预期为HttpAsyncClient#execute 的第三个参数。此解决方案不会阻塞您当前的线程。

【讨论】:

  • get() 如果我们使用 BasicAsyncResponseConsumer ,则只有当所有响应内容都存储在本地缓冲区中时才会调用。但这不是问题所在。我们希望直接流式传输响应正文,而不是将其存储在本地缓冲区中。
猜你喜欢
  • 2017-08-30
  • 2020-07-13
  • 2018-10-21
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-02
相关资源
最近更新 更多