Sunday 19 May 2024

Set Http client configurations via system properties

Using HttpClientBuilder#useSystemProperties method, we can set the http client configurations via system properties.

 

HttpClientBuilder#useSystemProperties  use system properties when creating and configuring default implementations.

 

a.   http.proxyHost

b.   http.proxyPort

c.    https.proxyHost

d.   https.proxyPort

e.   http.nonProxyHosts

f.     https.proxyUser

g.   http.proxyUser

h.   https.proxyPassword

i.     http.proxyPassword

j.     http.keepAlive

k.    http.agent

 

Example

System.setProperty("http.keepAlive", "true");
CloseableHttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();

Find the below working application.

 

UseSystemPropertiesDemo.java

package com.sample.app.httplclientbuilder;

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.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
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.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;

public class UseSystemPropertiesDemo {

	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) {

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

			}
		};
		
		System.setProperty("http.keepAlive", "true");

		try (CloseableHttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build()) {

			ClassicHttpRequest request = new HttpGet("http://localhost:8080/api/v1/employees/1");
			String response = httpClient.execute(request, responseHandler);
			
			System.out.println(response);

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

}


Previous                                                    Next                                                    Home

No comments:

Post a Comment