From HttpClient version 3 to version there have been many changes. The second example is definitely from HttpClient 4, so the first example is probably from the previous version.
Here is the code that will do your Google search, and read the result in line
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(60); connectionManager.setDefaultMaxPerRoute(6); try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build()) { HttpGet request = new HttpGet("http://www.google.com/search?q=httpClient"); request.setHeader("User-Agent", "HttpClient"); try (CloseableHttpResponse response = client.execute(request)) { MediaType mediaType = MediaType.parseMediaType(response.getFirstHeader("Content-Type").getValue()); Charset charSet = mediaType.getCharSet(); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); String body = CharStreams.toString(new InputStreamReader(is, charSet)); System.out.println("body = " + body); EntityUtils.consume(entity); } }
First, you probably want to create a connection pool so you can reuse the connection if you send multiple requests to the same server. A pool is usually created during application initialization, for example, as a Spring singleton bean.
I used ClosableHttpClient here because it works with load-try syntax and you need to close both HTTPClient and responseStream when you finish reading. HttpClient is actually a lightweight object, a state similar to a socket connection, and cookies are stored elsewhere.
I use Spring MediaType.parseMediaType () to get char encoding, and Guavas CharStreams to convert inputStream to String. In my case, google encoded content using latin-1 because the βsearchβ is βsΓΈgningβ in Danish.
The final step is to use EntityUtils.consume (entity) to ensure that all entity data has been read. If you use a connection pool, this is important because unread data will lead to disconnection and not reuse by the connection manager (this is very important if you use https).
source share