Java HttpClient POST, PUT and Patch Example with Body


Java HttpClient library from Apache is very good, it provides many interfaces to perform different operations like  POST, PUT, and PATCH.

One can also send String or URI encoded form and another payload very easily using the HttpEntity interface. You can easily add query strings and custom headers.

To post JSON string, XML, or simple String one can use StringEntity and for Form data, one can Use UrlEncodedFormEntity.

Here is an example of POST with JSON body

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'

Example of POST


public Map<String, String> executeGet(final String url, final Object payLoad, 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());
	}

	// can change for HttpPut, HttpPost, HttpPatch
	final HttpPost request = new HttpPost(builder.build());

	// Add headers from input map
	for (final Entry<String, String> elm : headers.entrySet()) {
		request.addHeader(elm.getKey(), elm.getValue());
	}
	
	request.setHeader("Accept", "application/json");
	request.setHeader("Content-type", "application/json");
	
	// Send Json String as body, can also send UrlEncodedFormEntity
	final StringEntity entity = new StringEntity(objectMapper.writeValueAsString(payLoad));
	request.setEntity(entity);

	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());
	}

}

}

In above example, you can change HttpPost to HttpPut pr HttpPatch class.


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.