Apache httpclient is the most efficient way to read a response

I am using apache httpcompnonents for httpclient. I want to use it in a multi-threaded application where the number of threads will be really high and there will be frequent HTTP calls. This is the code that I use to read the response after making the call.

HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity); 

I just want to confirm that this is the most efficient way to read the answer?

Thanks Hemant

+4
source share
1 answer

This is actually the most inefficient way to handle an HTTP response.

You most likely want to digest the contents of the response into a domain object of a certain type. So, what is the point of buffering it in memory as a string?

The recommended way to handle responses is to use a custom ResponseHandler , which can process content by streaming it directly from the underlying connection. An additional benefit of using ResponseHandler is that it completely eliminates the decision to release the connection and free up resources.

EDIT: changed sample code to use JSON

Here is an example of this using HttpClient 4.2 and the Jackson JSON processor. Stuff is considered your domain object with JSON bindings.

 ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() { @Override public Stuff handleResponse( final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException( statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } JsonFactory jsonf = new JsonFactory(); InputStream instream = entity.getContent(); // try - finally is not strictly necessary here // but is a good practice try { JsonParser jsonParser = jsonf.createParser(instream); // Use the parser to deserialize the object from the content stream return stuff; } finally { instream.close(); } } }; DefaultHttpClient client = new DefaultHttpClient(); Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh); 
+14
source

Source: https://habr.com/ru/post/1489633/


All Articles