Showing posts with label http-client. Show all posts
Showing posts with label http-client. Show all posts

Friday, 24 May 2024

Apache http client utility class

HttpClientUtil.java

package com.sample.app.util;

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.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.net.ssl.SSLContext;

import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
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 org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
import org.apache.hc.core5.ssl.SSLContexts;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class HttpClientUtil {
	private static final ObjectMapper objectMapper = new ObjectMapper();

	public static class HttpClientUtilBuilder {
		private Integer connectionTimeout = 5;
		private Integer socketTimeout = 5;
		private Integer timeToLive = 120;
		private Integer validateAfterInactivity = 30;
		private PoolConcurrencyPolicy poolConcurrencyPolicy = PoolConcurrencyPolicy.LAX;
		private PoolReusePolicy poolReusePolicy = PoolReusePolicy.LIFO;
		private Integer totalConnections = 200;
		private Integer maxConnectionsPerRoute = 25;
		private Integer responseTimeout = 15;

		public HttpClientUtilBuilder connectionTimeout(Integer connectionTimeout) {
			this.connectionTimeout = connectionTimeout;
			return this;
		}

		public HttpClientUtilBuilder socketTimeout(Integer socketTimeout) {
			this.socketTimeout = socketTimeout;
			return this;
		}

		public HttpClientUtilBuilder timeToLive(Integer timeToLive) {
			this.timeToLive = timeToLive;
			return this;
		}

		public HttpClientUtilBuilder validateAfterInactivity(Integer validateAfterInactivity) {
			this.validateAfterInactivity = validateAfterInactivity;
			return this;
		}

		public HttpClientUtilBuilder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) {
			this.poolConcurrencyPolicy = poolConcurrencyPolicy;
			return this;
		}

		public HttpClientUtilBuilder poolReusePolicy(PoolReusePolicy poolReusePolicy) {
			this.poolReusePolicy = poolReusePolicy;
			return this;
		}

		public HttpClientUtilBuilder totalConnections(Integer totalConnections) {
			this.totalConnections = totalConnections;
			return this;
		}

		public HttpClientUtilBuilder maxConnectionsPerRoute(Integer maxConnectionsPerRoute) {
			this.maxConnectionsPerRoute = maxConnectionsPerRoute;
			return this;
		}

		public HttpClientUtilBuilder responseTimeout(Integer responseTimeout) {
			this.responseTimeout = responseTimeout;
			return this;
		}

		public HttpClientUtil build() throws Exception {
			return new HttpClientUtil(this);
		}
	}

	// All timeouts are in seconds
	private Integer connectionTimeout;
	private Integer socketTimeout;
	private Integer timeToLive;
	private Integer validateAfterInactivity;
	private PoolConcurrencyPolicy poolConcurrencyPolicy;
	private PoolReusePolicy poolReusePolicy;
	private Integer totalConnections;
	private Integer maxConnectionsPerRoute;
	private HttpClientConnectionManager httpClientConnectionManager;
	private Integer responseTimeout;

	public HttpClientUtil(HttpClientUtilBuilder builder) throws Exception {
		this.connectionTimeout = builder.connectionTimeout;
		this.socketTimeout = builder.socketTimeout;
		this.timeToLive = builder.timeToLive;
		this.validateAfterInactivity = builder.validateAfterInactivity;
		this.poolConcurrencyPolicy = builder.poolConcurrencyPolicy;
		this.poolReusePolicy = builder.poolReusePolicy;
		this.totalConnections = builder.totalConnections;
		this.maxConnectionsPerRoute = builder.maxConnectionsPerRoute;
		this.responseTimeout = builder.responseTimeout;
		this.httpClientConnectionManager = getConnectionManager();

	}

	public HttpClientUtil(HttpClientConnectionManager connectionManager, Integer responseTimeout) {
		this.httpClientConnectionManager = connectionManager;
		this.responseTimeout = responseTimeout;
	}

	public HttpClientConnectionManager getConnectionManager() throws Exception {

		// setting up an SSLContext with custom trust management, where it will trust
		// any certificate presented by the server
		SSLContext sslContext = SSLContexts.custom()
				.loadTrustMaterial((X509Certificate[] chain, String authType) -> true).build();

		final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
				NoopHostnameVerifier.INSTANCE);

		ConnectionConfig connectionConfig = ConnectionConfig.custom()
				.setConnectTimeout(this.connectionTimeout, TimeUnit.SECONDS)
				.setSocketTimeout(this.socketTimeout, TimeUnit.SECONDS).setTimeToLive(this.timeToLive, TimeUnit.SECONDS)
				.setValidateAfterInactivity(this.validateAfterInactivity, TimeUnit.SECONDS).build();

		PoolingHttpClientConnectionManager manager = PoolingHttpClientConnectionManagerBuilder.create()
				.setPoolConcurrencyPolicy(this.poolConcurrencyPolicy).setConnPoolPolicy(this.poolReusePolicy)
				.setDefaultConnectionConfig(connectionConfig).setSSLSocketFactory(sslsf)
				.setMaxConnTotal(this.totalConnections).setMaxConnPerRoute(this.maxConnectionsPerRoute).build();

		return manager;

	}

	public CloseableHttpClient httpClient() {

		RequestConfig.Builder builder = RequestConfig.custom();
		builder.setResponseTimeout(responseTimeout, TimeUnit.SECONDS);
		RequestConfig requestConfig = builder.build();

		return HttpClients.custom().setConnectionManager(httpClientConnectionManager)
				.setDefaultRequestConfig(requestConfig).build();
	}

	static {
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	}

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

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

			if (response.getCode() != HttpStatus.SC_OK && response.getCode() != HttpStatus.SC_CREATED) {
				throw new IOException("Error: HTTP request failed with status code: " + response.getCode()
						+ " message: " + response.getReasonPhrase());
			}
			HttpEntity httpEntity = response.getEntity();

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

		}
	};

	private static <T> T httpRequest(CloseableHttpClient httpClient, ClassicHttpRequest request, Class<T> clazz)
			throws Exception {
		try {
			String response = httpClient.execute(request, responseHandler);

			if (clazz != null) {
				return objectMapper.readValue(response, clazz);
			}
			return null;

		} catch (Exception e) {
			throw new Exception("Error: No entity content found in response");
		}
	}

	private static void setHeaders(ClassicHttpRequest request, Map<String, String> headers) {
		if (headers != null) {
			for (Map.Entry<String, String> header : headers.entrySet()) {
				request.addHeader(header.getKey(), header.getValue());
			}
		}
	}

	public static <T> T get(CloseableHttpClient httpClient, String url, Class<T> clazz, Map<String, String> headers)
			throws Exception {
		HttpGet request = new HttpGet(url);
		setHeaders(request, headers);
		return httpRequest(httpClient, request, clazz);
	}

	public static <T, D> T post(CloseableHttpClient httpClient, String url, D data, Class<T> clazz,
			Map<String, String> headers) throws Exception {
		HttpPost request = new HttpPost(url);
		setHeaders(request, headers);
		request.setEntity(new StringEntity(objectMapper.writeValueAsString(data)));
		return httpRequest(httpClient, request, clazz);
	}

	public static <T, D> T put(CloseableHttpClient httpClient, String url, D data, Class<T> clazz,
			Map<String, String> headers) throws Exception {
		HttpPut request = new HttpPut(url);
		setHeaders(request, headers);
		request.setEntity(new StringEntity(objectMapper.writeValueAsString(data)));
		return httpRequest(httpClient, request, clazz);
	}

	public static void delete(CloseableHttpClient httpClient, String url, Map<String, String> headers)
			throws Exception {
		HttpDelete request = new HttpDelete(url);
		setHeaders(request, headers);
		httpRequest(httpClient, request, null);
	}

}

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 + "]";
	}

	
}

HttpClientUtilDemo.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;

import com.sample.app.dto.Employee;
import com.sample.app.util.HttpClientUtil;

public class HttpClientUtilDemo {

	public static void main(String[] args) throws Exception {
		HttpClientUtil httpClientUtil = new HttpClientUtil.HttpClientUtilBuilder().connectionTimeout(10)
				.maxConnectionsPerRoute(30).totalConnections(100).poolConcurrencyPolicy(PoolConcurrencyPolicy.LAX)
				.poolReusePolicy(PoolReusePolicy.FIFO).responseTimeout(10).socketTimeout(5).timeToLive(300)
				.validateAfterInactivity(120).build();

		try (CloseableHttpClient httpClient = httpClientUtil.httpClient();) {
			String url = "http://localhost:8080/api/v1/employees/1";

			Map<String, String> headers = new HashMap<>();
			headers.put(HttpHeaders.CONTENT_TYPE, "application/json");

			System.out.println("Employee with id 1");
			Employee emp = HttpClientUtil.get(httpClient, url, Employee.class, headers);
			System.out.println(emp);

			System.out.println("\nUpdating employee with id 1");
			Employee emp1 = new Employee();
			emp1.setFirstName("Chamu");
			emp1.setLastName("Maj");
			HttpClientUtil.put(httpClient, url, emp1, Employee.class, headers);

			emp1 = HttpClientUtil.get(httpClient, url, Employee.class, headers);
			System.out.println(emp1);

			System.out.println("\nCreate new employee");
			Employee emp2 = new Employee();
			emp2.setFirstName("Gopi");
			emp2.setLastName("Battu");
			emp2 = HttpClientUtil.post(httpClient, "http://localhost:8080/api/v1/employees", emp2, Employee.class,
					headers);
			System.out.println(emp2);

		}

	}

}

Output

Employee with id 1
Employee [id=1, firstName=Deepak, lastName=Moud]

Updating employee with id 1
Employee [id=1, firstName=Chamu, lastName=Maj]

Create new employee
Employee [id=10, firstName=Gopi, lastName=Battu]

Previous                                                    Next                                                    Home

Making HTTP Requests with the Fluent API of Http Client

The Apache HttpClient Fluent API is a simplified and fluent interface for making HTTP requests and processing responses in Apache HttpClient. It provides a more concise and intuitive way to interact with HTTP resources compared to the traditional approach.

Example of GET API

Request request = Request.get(url);
Response response = request.execute();
String respMsg = response.handleResponse(responseHandler);

 Example of POST API

request = Request
.post("http://localhost:8080/api/v1/employees")
.addHeader("Content-Type", "application/json")
.bodyString(payload, ContentType.APPLICATION_JSON);

Find the below working application.

 

HttpFluentApiDemo.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.fluent.Request;
import org.apache.hc.client5.http.fluent.Response;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;

public class HttpFluentApiDemo {

    private 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"));
        }

    }

    private static 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);
            }

        }
    };

    public static void main(String[] args) throws IOException {
        String url = "http://localhost:8080/api/v1/employees/1";

        Request request = Request.get(url);
        Response response = request.execute();
        String respMsg = response.handleResponse(responseHandler);
        System.out.println(respMsg);

        String payload = "{\n" + "  \"firstName\": \"Abhishek\",\n" + "  \"lastName\": \"Ramesh\"\n" + "}";

        request = Request.post("http://localhost:8080/api/v1/employees").addHeader("Content-Type", "application/json")
                .bodyString(payload, ContentType.APPLICATION_JSON);
        response = request.execute();
        respMsg = response.handleResponse(responseHandler);
        System.out.println(respMsg);
    }

}

Output

{"id":1,"firstName":"Deepak","lastName":"Moud"}
{"id":13,"firstName":"Abhishek","lastName":"Ramesh"}

While calling the execute method, you can even specify the http client responsible to execute this API.

Response execute(final CloseableHttpClient client)

  

Previous                                                    Next                                                    Home

Thursday, 23 May 2024

How to Configure a Credential Provider in Apache HttpClient?

In this post, I am going to explain how to set a credential provider to http client.

Step 1: Define Authentication Scope instance.

HttpHost targetHost = new HttpHost("http", "localhost", 8080);
AuthScope authScope = new AuthScope(targetHost);

AuthScope in Apache HttpClient represents the scope of authentication, including the host, port, realm, and authentication scheme. It's used to determine which credentials to use for a particular request based on the target host and the authentication credentials available. In the provided code, it's initialized with just the target host, but you can customize it further based on your specific authentication requirements.

 

Step 2: Define CredentialsProvider instance.

private static CredentialsProvider provider() {
	final BasicCredentialsProvider provider = new BasicCredentialsProvider();
	provider.setCredentials(authScope, new UsernamePasswordCredentials(USERNAME, PASSWORD.toCharArray()));
	return provider;
}

The provided snippet defines a method named provider() that returns a CredentialsProvider object. Within the method, it initializes a BasicCredentialsProvider named provider. This BasicCredentialsProvider is responsible for managing credentials for authentication. It sets the credentials for a specific authentication scope (authScope) using a UsernamePasswordCredentials object, which takes a username and password as arguments.

 

Step 3: Define CredsInterceptor that set the request Authorizaiton header based on the configured credential providers.

class CredsInterceptor implements HttpRequestInterceptor {

    @Override
    public void process(HttpRequest request, EntityDetails entity, HttpContext context)
            throws HttpException, IOException {
        CredentialsProvider provider = HttpClientContext.adapt(context).getCredentialsProvider();

        if (provider == null) {
            return;
        }

        Credentials credentials = provider.getCredentials(authScope, context);

        if (credentials instanceof UsernamePasswordCredentials) {
            UsernamePasswordCredentials creds = (UsernamePasswordCredentials) credentials;
            String encodedCredentials = Base64.getEncoder()
                    .encodeToString((creds.getUserName() + ":" + new String(creds.getUserPassword()))
                            .getBytes(StandardCharsets.UTF_8));
            request.addHeader("Authorization", "Basic " + encodedCredentials);
        }
    }

}

The provided code defines a Java class named CredsInterceptor, which implements the HttpRequestInterceptor interface. This class is intended to intercept HTTP requests and add authentication credentials to the request headers. Within the process method, it first obtains the CredentialsProvider from the HttpContext. If no credentials provider is found, it returns early. If a credentials provider is available, it retrieves the credentials for the specified authentication scope from the provider. It then checks if the credentials are of type UsernamePasswordCredentials, and if so, it encodes the username and password using Base64 encoding and adds them to the request headers with the key "Authorization". This interceptor essentially injects basic authentication credentials into outgoing HTTP requests based on the provided credentials provider and authentication scope.

 

Step 4: Build the http client with the CredentialsProvider configured in step 2. 

CloseableHttpClient httpClient = HttpClients
.custom()
.addRequestInterceptorFirst(new CredsInterceptor())
.setDefaultCredentialsProvider(provider())
.build();

Find the below working application.

 

CredentialsProviderDemo.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.Base64;
import java.util.stream.Collectors;

import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.Credentials;
import org.apache.hc.client5.http.auth.CredentialsProvider;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpRequestInterceptor;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.protocol.HttpContext;

public class CredentialsProviderDemo {

    private static HttpHost targetHost = new HttpHost("http", "localhost", 8080);
    private static AuthScope authScope = new AuthScope(targetHost);
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "password123";

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

    }

    private static class CredsInterceptor implements HttpRequestInterceptor {

        @Override
        public void process(HttpRequest request, EntityDetails entity, HttpContext context)
                throws HttpException, IOException {
            CredentialsProvider provider = HttpClientContext.adapt(context).getCredentialsProvider();

            if (provider == null) {
                return;
            }

            Credentials credentials = provider.getCredentials(authScope, context);

            if (credentials instanceof UsernamePasswordCredentials) {
                UsernamePasswordCredentials creds = (UsernamePasswordCredentials) credentials;
                String encodedCredentials = Base64.getEncoder()
                        .encodeToString((creds.getUserName() + ":" + new String(creds.getUserPassword()))
                                .getBytes(StandardCharsets.UTF_8));
                request.addHeader("Authorization", "Basic " + encodedCredentials);
            }
        }

    }

    private static CredentialsProvider provider() {
        final BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(authScope, new UsernamePasswordCredentials(USERNAME, PASSWORD.toCharArray()));
        return provider;
    }

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

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

                System.out.println("Response code : " + response.getCode());

                HttpEntity httpEntity = response.getEntity();

                try (InputStream is = httpEntity.getContent()) {
                    String result = inputStreamToString(is, StandardCharsets.UTF_8);
                    System.out.println(result);
                }

                return null;

            }
        };

        String url = "http://localhost:8080/api/v1/basic-auth";

        try (CloseableHttpClient httpClient = HttpClients.custom().addRequestInterceptorFirst(new CredsInterceptor())
                .setDefaultCredentialsProvider(provider()).build();) {

            HttpGet httpGet = new HttpGet(url);
            httpClient.execute(httpGet, responseHandler);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




 



 

Previous                                                    Next                                                    Home

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