HttpClient Java Get Example with Query String and Custom Headers


Apache HttpClient java library is my most preferred HttpClient library for making HTTP requests. One can easily add parameters, body, and custom headers with clean interfaces.

Since version 4.0 it also provides EntityUtils to read the response from HttpResponse into string and byte arrays.

Here is a complete example to make get requests with parameres and headers. It also reads the JSON response body and serializes it into Map using the Jackson ObjectMapper class. You can easily serialize JSON into different objects using this.

Gradle Dependency

 // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
api 'org.apache.httpcomponents:httpclient:4.5.12'

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
api 'com.fasterxml.jackson.core:jackson-databind:2.11.2'

Java Example

public Map<String, String> executeGet(final String url, final Map<String, String> headers,
		final Map<String, String> params) throws Throwable, Exception {
	final CloseableHttpClient httpClient = HttpClientBuilder.create().build();

	final ObjectMapper objectMapper = new ObjectMapper();
	
	// Add query strings to URL
	URIBuilder builder = new URIBuilder(url);

	for (final Entry<String, String> elm : params.entrySet()) {
		builder = builder.setParameter(elm.getKey(), elm.getValue());
	}

	final HttpGet request = new HttpGet(builder.build());

	// Add headers from input map
	for (final Entry<String, String> elm : headers.entrySet()) {
		request.addHeader(elm.getKey(), elm.getValue());
	}

	try (final CloseableHttpResponse response = httpClient.execute(request)) {
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			final Map<String, String> obj = new HashMap<String, String>();
			// Read response string using EntityUtils class of Apache http client library
			// Serialize json string into map or any other object
			return objectMapper.readValue(EntityUtils.toString(response.getEntity()), obj.getClass());

		} else {
			throw new Exception(String.format("Response status code was %i and response was %s",
					response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity())));
		}
	} catch (final ClientProtocolException e) {
		throw new Exception("Client protocol Exception occured while executing retuest", e.getCause());
	} catch (final IOException e) {
		throw new Exception("IO Exception occured while executing retuest", e.getCause());
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.