1

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Karan Tibrewal
  • 467
  • 1
  • 5
  • 4

1 Answers1

1

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • get() will be called only when all the response content has been stored in a local buffer if we use BasicAsyncResponseConsumer . But thats not what the ask is. We want to stream the response body directly and not store it in local buffer. – lostintranslation May 07 '18 at 13:25