Thursday, 23 May 2024

Step-by-Step Guide to Making POST Requests with Apache HttpClient

Using HttpPost class, we can submit a POST request.

 

Example

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/employees");
Employee emp = new Employee();
emp.setFirstName("Joel");
emp.setLastName("Chelli");

httpPost.setHeader("Content-Type", "application/json");

ObjectMapper objectMapper = new ObjectMapper();

httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(emp)));

String response = httpClient.execute(httpPost, responseHandler);

Above code snippet demonstrates how to make an HTTP POST request to a specified URL (http://localhost:8080/api/v1/employees) with JSON data representing an Employee object.

 

HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/employees");

Creates an HTTP POST request object targeting the specified URL.

 

Employee emp = new Employee();

emp.setFirstName("Joel");

emp.setLastName("Chelli");

Creates a new Employee object. Sets the first name and last name properties of the Employee object to "Joel" and "Chelli", respectively.

 

httpPost.setHeader("Content-Type", "application/json");

Sets the Content-Type header of the HTTP POST request to indicate that the request body contains JSON data.

 

ObjectMapper objectMapper = new ObjectMapper();

Creates an instance of ObjectMapper, which is a part of Jackson library used for JSON serialization and deserialization.

 

httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(emp)));

Serializes the Employee object emp into a JSON string using the ObjectMapper, then creates a StringEntity from that JSON string and sets it as the entity of the HTTP POST request. This means the JSON representation of the Employee object will be sent as the request body.

 

String response = httpClient.execute(httpPost, responseHandler);

Executes the HTTP POST request using an instance of HttpClient (httpClient) and a response handler (responseHandler). The response from the server is stored in the response variable as a string.

 

Overall, this code snippet sends an HTTP POST request to the specified URL with JSON data representing an Employee object in the request body and retrieves the response from the server.

 

Find the below working application.

 

Employee.java

package com.sample.app.dto;

public class Employee {
	private Integer id;
	private String firstName;
	private String lastName;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
	}

	
}

PostMethodExample.java

package com.sample.app.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.StringEntity;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.dto.Employee;

public class PostMethodExample {

	public static String inputStreamToString(InputStream inputStream, Charset charSet) throws IOException {

		try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charSet))) {
			return reader.lines().collect(Collectors.joining("\n"));
		}

	}

	public static void main(String[] args) throws Exception {

		HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
			@Override
			public String handleResponse(final ClassicHttpResponse response) throws IOException, ParseException {

				HttpEntity httpEntity = response.getEntity();

				try (InputStream is = httpEntity.getContent()) {
					return inputStreamToString(is, StandardCharsets.UTF_8);
				}

			}
		};

		try (CloseableHttpClient httpClient = HttpClients.custom().build();) {

			HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/employees");
			Employee emp = new Employee();
			emp.setFirstName("Joel");
			emp.setLastName("Chelli");

			httpPost.setHeader("Content-Type", "application/json");

			ObjectMapper objectMapper = new ObjectMapper();

			httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(emp)));

			String response = httpClient.execute(httpPost, responseHandler);
			System.out.println(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment