1

我是 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 内容?

4

1 回答 1

1

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

一,调用返回的 by get(),阻塞直到结果准备好。结果准备好后,将返回可用于检索内容的对象。有一个. 阅读它,但你认为是合适的。Futureexecuteget()HttpResponsegetEntityHttpEntityInputStream

第二,提供一个HttpAsyncResponseConsumerBasicAsyncResponseConsumer读取(并关闭)HttpResponse'sHttpEntity并生成一个可以被FutureCallback预期作为HttpAsyncClient#execute. 此解决方案不会阻止您当前的线程。

于 2016-06-25T01:31:55.973 回答