Reputation: 507
I'm new to Java NIO. I'm using it to make HTTP Get requests. The requests executes properly, but I am unable to figure out how to get the content of the response.
For example,
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)
Now how do I get the content of the response? On printing future, I get the following:
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]
My response (on the browser) is 903 characters, so I know the it makes the request correctly. However, how do I print out the json content of the result?
Upvotes: 1
Views: 2867
Reputation: 280102
There are a couple of ways for you to approach this.
One, call get()
on the Future
returned by execute
, blocking until a result is ready. Once the result is ready, get()
will return the HttpResponse
object which you can use to retrieve the content with getEntity
. The HttpEntity
has an InputStream
. Read it however you think is appropriate.
Two, provide a smarter HttpAsyncResponseConsumer
implementation than BasicAsyncResponseConsumer
which reads (and closes) the HttpResponse
's HttpEntity
and produces a value that can be consumed by the FutureCallback
value that is expected as the third argument to HttpAsyncClient#execute
. This solution will not block your current thread.
Upvotes: 1