Skip to content

Instantly share code, notes, and snippets.

@vidhya03
Created April 14, 2024 03:20
Show Gist options
  • Save vidhya03/a41a85bc38e3f295321bde42bb57146b to your computer and use it in GitHub Desktop.
Save vidhya03/a41a85bc38e3f295321bde42bb57146b to your computer and use it in GitHub Desktop.
This is for blog - java17 upgrade and under sub section - Upgrading to Apache HttpClient 5
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
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.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@Configuration
public class RestTemplateConfiguration {
private final static Logger logger = LoggerFactory.getLogger(RestTemplateConfiguration.class);
@Autowired
private Environment environment;
@Autowired
private ApplicationProperties appconfig;
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public ClientHttpRequestFactory clientHttpRequestFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(getConnectionManager())
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(StandardCookieSpec.STRICT)
.build())
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
String proxyHost = environment.getProperty("proxy.host");
String proxyPortStr = environment.getProperty("proxy.port");
Integer proxyPort = null;
if (!StringUtils.isEmpty(proxyPortStr)) {
proxyPort = Integer.valueOf(proxyPortStr);
}
// Proxy
if (!StringUtils.isEmpty(proxyHost) && proxyPort != null) {
requestFactory = new HttpComponentsClientHttpRequestFactory(
HttpClients.custom()
.setProxy(new org.apache.hc.core5.http.HttpHost(proxyHost, proxyPort))
.build());
logger.info("Using proxy {}:{}", proxyHost, proxyPort);
} else {
requestFactory = new HttpComponentsClientHttpRequestFactory();
}
return requestFactory;
}
public PoolingHttpClientConnectionManager getConnectionManager() throws IOException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IOException(e);
}
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
.setSslContext(org.apache.hc.core5.ssl.SSLContexts.createSystemDefault())
.setTlsVersions(TLS.V_1_3)
.build())
.setSSLSocketFactory(csf)
.setDefaultSocketConfig(SocketConfig.custom()
.setSoTimeout(Timeout.ofMinutes(10))
.build())
.setPoolConcurrencyPolicy(PoolConcurrencyPolicy.STRICT)
.setConnPoolPolicy(PoolReusePolicy.LIFO)
.setDefaultConnectionConfig(ConnectionConfig.custom()
.setSocketTimeout(Timeout.ofMilliseconds(appconfig.getConfig().getReadTimeout()))
.setConnectTimeout(Timeout.ofMilliseconds(appconfig.getConfig().getConnectTimeout()))
.setTimeToLive(TimeValue.ofMinutes(10))
.build())
.build();
return connectionManager;
}
}
import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
@Configuration
public class RestTemplateConfiguration {
private final static Logger logger = LoggerFactory.getLogger(RestTemplateConfiguration.class);
@Autowired
private Environment environment;
@Autowired
private ApplicationProperties appconfig;
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public ClientHttpRequestFactory clientHttpRequestFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpComponentsClientHttpRequestFactory requestFactory = null;
String proxyHost = environment.getProperty("proxy.host");
String proxyPortStr = environment.getProperty("proxy.port");
Integer proxyPort = null;
if (!StringUtils.isEmpty(proxyPortStr)) {
proxyPort = Integer.valueOf(proxyPortStr);
}
// Proxy
if (!StringUtils.isEmpty(proxyHost) && proxyPort != null) {
requestFactory = new HttpComponentsClientHttpRequestFactory(
HttpClients.custom()
.setProxy(new HttpHost(proxyHost, proxyPort))
.build());
logger.info("Using proxy {}:{}", proxyHost, proxyPort);
} else {
requestFactory = new HttpComponentsClientHttpRequestFactory();
}
requestFactory.setConnectTimeout(appconfig.getConfig().getConnectTimeout());
requestFactory.setReadTimeout(appconfig.getConfig().getReadTimeout());
// SSL
TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
requestFactory.setHttpClient(httpClient);
return requestFactory;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment