Move the code to httpclient

This commit is contained in:
YuCheng Hu 2024-05-02 12:20:52 -04:00
parent 9c08c5559c
commit 002f2c8ede
Signed by: honeymoose
GPG Key ID: D74AE0B33A8002EC
73 changed files with 40 additions and 3184 deletions

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,16 +0,0 @@
## Apache HttpClient
This module contains articles about Apache HttpClient
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/apache-httpclient-tls)
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- More articles: [[<-- prev]](../apache-httpclient)

View File

@ -1,86 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-httpclient-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-httpclient-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>${httpclient5.version}</version>
</dependency>
<!-- rest template -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<!-- Webclient -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-client-java</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>apache-httpclient-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<mockserver.version>5.11.2</mockserver.version>
<httpclient5.version>5.2.1</httpclient5.version>
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
</properties>
</project>

View File

@ -1,17 +0,0 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestTemplate;
public class SpringRestTemplateUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseRestTemplate_thenCorrect() {
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(DUMMY_URL, String.class);
System.out.println(response);
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.junit.jupiter.api.Test;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class SpringWebClientUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
void whenUseWebClientRetrieve_thenCorrect() {
WebClient webClient = WebClient.create(DUMMY_URL);
Mono<String> body = webClient.get().retrieve().bodyToMono(String.class);
String s = body.block();
System.out.println(s);
}
}

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,19 +0,0 @@
## Apache HttpClient 4
This module contains articles about Apache HttpClient 4.5
### Relevant Articles
- [Apache HttpClient Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl)
- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout)
- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- [Retrying Requests using Apache HttpClient](https://www.baeldung.com/java-retrying-requests-using-apache-httpclient)
- [Apache HttpClient Follow Redirects for POST](https://www.baeldung.com/httpclient-redirect-on-http-post)
### Running the Tests
To run the live tests, use the command: mvn clean install -Plive
This will start an embedded Jetty server on port 8082 using the Cargo plugin configured in the pom.xml file,
for the live Maven profile

View File

@ -1,240 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-httpclient4</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>apache-httpclient4</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring-oxm.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>${httpasyncclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>httpclient-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<spring-oxm.version>6.1.4</spring-oxm.version>
<!-- util -->
<commons-codec.version>1.16.0</commons-codec.version>
<httpasyncclient.version>4.1.5</httpasyncclient.version>
<!-- testing -->
<wiremock.version>3.3.1</wiremock.version>
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<mockserver.version>5.11.2</mockserver.version>
</properties>
</project>

View File

@ -1,30 +0,0 @@
package com.baeldung.basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final PrintWriter writer = response.getWriter();
writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
}
@Override
public void afterPropertiesSet() {
setRealmName("Baeldung");
super.afterPropertiesSet();
}
}

View File

@ -1,39 +0,0 @@
package com.baeldung.client;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.client.AuthCache;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory {
HttpHost host;
public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
super();
this.host = host;
}
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
return createHttpContext();
}
private HttpContext createHttpContext() {
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
return localcontext;
}
}

View File

@ -1,44 +0,0 @@
package com.baeldung.client;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RestTemplateFactory implements FactoryBean<RestTemplate>, InitializingBean {
private RestTemplate restTemplate;
public RestTemplateFactory() {
super();
}
// API
@Override
public RestTemplate getObject() {
return restTemplate;
}
@Override
public Class<RestTemplate> getObjectType() {
return RestTemplate.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() {
HttpHost host = new HttpHost("localhost", 8082, "http");
final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
restTemplate = new RestTemplate(requestFactory);
restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass"));
}
}

View File

@ -1,16 +0,0 @@
package com.baeldung.client.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.baeldung.client")
public class ClientConfig {
public ClientConfig() {
super();
}
// beans
}

View File

@ -1,18 +0,0 @@
package com.baeldung.filter;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}

View File

@ -1,51 +0,0 @@
package com.baeldung.filter;
import com.baeldung.security.RestAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
final SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
super.onAuthenticationSuccess(request, response, authentication);
return;
}
final String targetUrlParameter = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
return;
}
clearAuthenticationAttributes(request);
// Use the DefaultSavedRequest URL
// final String targetUrl = savedRequest.getRedirectUrl();
// logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
// getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
public void setRequestCache(final RequestCache requestCache) {
this.requestCache = requestCache;
}
}

View File

@ -1,23 +0,0 @@
package com.baeldung.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
/**
* The Entry Point will not redirect to any sort of Login - it will return the 401
*/
@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}

View File

@ -1,16 +0,0 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
@ComponentScan("com.baeldung.security")
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.spring;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.web")
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
// beans
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
//
}

View File

@ -1,64 +0,0 @@
package com.baeldung.tlsversion;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}

View File

@ -1,31 +0,0 @@
package com.baeldung.web.controller;
import com.baeldung.web.dto.Bar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/bars")
public class BarController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public BarController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Bar findOne(@PathVariable("id") final Long id) {
return new Bar();
}
}

View File

@ -1,33 +0,0 @@
package com.baeldung.web.controller;
import com.baeldung.web.dto.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/foos")
public class FooController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public FooController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ROLE_USER')")
public Foo findOne(@PathVariable("id") final Long id) {
return new Foo();
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.web.dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Bar implements Serializable {
public Bar() {
super();
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.web.dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Foo implements Serializable {
public Foo() {
super();
}
}

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<http create-session="stateless" use-expressions="true">
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="{noop}user1Pass" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
<global-method-security pre-post-annotations="enabled"/>
<beans:bean id="myBasicAuthenticationEntryPoint" class="com.baeldung.basic.MyBasicAuthenticationEntryPoint" />
</beans:beans>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >
</beans>

View File

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<display-name>Spring Security Custom Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -1,56 +0,0 @@
package com.baeldung;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import java.io.IOException;
import java.net.ServerSocket;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
public class GetRequestMockServer {
public static ClientAndServer mockServer;
public static int serverPort;
public static String simplePathUrl;
public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String SIMPLE_PATH = "/httpclient-simple/api/bars/1";
@BeforeAll
static void startServer() throws IOException {
serverPort = getFreePort();
System.out.println("Free port " + serverPort);
mockServer = startClientAndServer(serverPort);
simplePathUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + SIMPLE_PATH;
mockGetRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
private static void mockGetRequest() {
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
client.when(request().withPath(SIMPLE_PATH)
.withMethod("GET"))
.respond(response().withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}"));
}
private static int getFreePort() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}

View File

@ -1,101 +0,0 @@
package com.baeldung.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.baeldung.GetRequestMockServer;
class ClientLiveTest extends GetRequestMockServer {
@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
final HttpGet getMethod = new HttpGet(simplePathUrl);
try (final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build()) {
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
}
@Test
void givenAcceptingAllCertificates_whenUsingRestTemplate_thenCorrect() {
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
void whenHttpsUrlIsConsumed_thenException() {
String urlOverHttps = "https://localhost:"+serverPort+"/httpclient-simple/api/bars/1";
HttpGet getMethod = new HttpGet(urlOverHttps);
assertThrows(SSLHandshakeException.class, () -> {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
});
}
}

View File

@ -1,38 +0,0 @@
package com.baeldung.client;
import java.io.IOException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.Test;
import com.baeldung.GetRequestMockServer;
import com.baeldung.httpclient.ResponseUtil;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
*/
class HttpClientSandboxLiveTest extends GetRequestMockServer {
@Test
final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final AuthScope authscp = new AuthScope("localhost", 8080);
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1");
final CloseableHttpResponse response = client.execute(httpGet);
System.out.println(response.getStatusLine());
ResponseUtil.closeResponse(response);
}
}

View File

@ -1,92 +0,0 @@
package com.baeldung.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build
* */
class RestClientV4LiveManualTest {
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
@Test
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet getMethod = new HttpGet(urlOverHttps);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect(){
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String urlOverHttps = "https://localhost:8082/httpclient-simple";
HttpGet getMethod = new HttpGet(urlOverHttps);
HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}

View File

@ -1,18 +0,0 @@
package com.baeldung.httpclient;
import java.io.IOException;
import org.apache.http.impl.client.CloseableHttpClient;
public final class ClientUtil {
private ClientUtil(){}
public static void closeClient(CloseableHttpClient client) throws IOException {
if (client == null) {
return;
}
client.close();
}
}

View File

@ -1,177 +0,0 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.junit.jupiter.api.Test;
import com.baeldung.GetRequestMockServer;
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
private static final String HOST_WITH_PROXY = "http://httpbin.org/";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";// "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1";
private static final String DEFAULT_USER = "test";// "user1";
private static final String DEFAULT_PASS = "test";// "user1Pass";
private static final String HOST_WITH_COOKIE = "http://yuilibrary.com/yui/docs/cookie/cookie-simple-example.html"; // "http://github.com";
private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com";
private static final String COOKIE_NAME = "example"; // "JSESSIONID";
// tests
@Test
void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpGet request = new HttpGet(HOST);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build();
client.start();
final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" };
final GetThread[] threads = new GetThread[toGet.length];
for (int i = 0; i < threads.length; i++) {
final HttpGet request = new HttpGet(toGet[i]);
threads[i] = new GetThread(client, request);
}
for (final GetThread thread : threads) {
thread.start();
}
for (final GetThread thread : threads) {
thread.join();
}
}
@Test
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
final HttpGet request = new HttpGet(HOST_WITH_PROXY);
request.setConfig(config);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_SSL);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
cookie.setDomain(COOKIE_DOMAIN);
cookie.setPath("/");
cookieStore.addCookie(cookie);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
final Future<HttpResponse> future = client.execute(request, localContext, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, creds);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
client.start();
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
static class GetThread extends Thread {
private final CloseableHttpAsyncClient client;
private final HttpContext context;
private final HttpGet request;
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
this.client = client;
context = HttpClientContext.create();
this.request = request;
}
@Override
public void run() {
try {
final Future<HttpResponse> future = client.execute(request, context, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} catch (final Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
}
}
}

View File

@ -1,59 +0,0 @@
package com.baeldung.httpclient;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class HttpClientCancelRequestV4LiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@BeforeEach
public final void before() {
instance = HttpClientBuilder.create().build();
}
@AfterEach
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
@Test
final void whenRequestIsCanceled_thenCorrect() throws IOException {
instance = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
response = instance.execute(request);
try {
final HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
entity.getContent().close();
}
System.out.println("----------------------------------------");
// Do not feel like reading the response body
// Call abort on the request object
request.abort();
} finally {
response.close();
}
}
}

View File

@ -1,204 +0,0 @@
package com.baeldung.httpclient;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
class HttpClientCookBookV4LiveTest {
private static final String SAMPLE_GET_URL = "http://www.google.com";
private static final String SAMPLE_POST_URL = "http://www.github.com";
private CloseableHttpClient client;
private CloseableHttpResponse response;
@BeforeEach
public final void before() {
client = HttpClientBuilder.create().build();
}
@AfterEach
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
ClientUtil.closeClient(client);
}
@Test
void givenGetRequestExecuted_thenCorrectStatusCode() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
response = client.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenGetRequestExecuted_thenCorrectContentMimeType() throws IOException {
CloseableHttpResponse response = client.execute(new HttpGet(SAMPLE_GET_URL));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));
}
@Test
void givenGetRequestExecuted_thenCorrectResponse() throws IOException {
CloseableHttpResponse response = client.execute(new HttpGet(SAMPLE_GET_URL));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
}
@Test
void givenLowSocketTimeOut_whenExecutingRequestWithTimeout_thenException() throws IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000)
.setConnectTimeout(1000)
.setSocketTimeout(20)
.build();
HttpGet request = new HttpGet(SAMPLE_POST_URL);
request.setConfig(requestConfig);
assertThrows(SocketTimeoutException.class, () -> {
response = client.execute(request);
});
}
@Test
void givenLowSocketTimeOut_whenSettingTimeoutOnTheClient_thenException(){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000)
.setConnectTimeout(1000)
.setSocketTimeout(20).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
client = builder.build();
HttpGet request = new HttpGet(SAMPLE_GET_URL);
assertThrows(SocketTimeoutException.class, () -> {
response = client.execute(request);
});
}
@Test
void whenExecutingPostRequest_thenNoExceptions() throws IOException {
response = client.execute(new HttpPost(SAMPLE_POST_URL));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
@Test
void givenParametersAddedToRequest_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_POST_URL);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
response = client.execute(new HttpPost(SAMPLE_POST_URL));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
CloseableHttpClient client = HttpClientBuilder.create()
.disableRedirectHandling()
.build();
CloseableHttpResponse response = client.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
@Test
void givenHeadersAddedToRequest_thenCorrect() throws IOException {
HttpGet request = new HttpGet(SAMPLE_GET_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
CloseableHttpResponse response = client.execute(new HttpGet(SAMPLE_GET_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
}
@Test
void givenStreamIsClosed_thenCloseResponse() throws IOException {
response = client.execute(new HttpGet(SAMPLE_GET_URL));
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
}
@Test
void givenAutoClosableClient_thenCorrect() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
// handle response;
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// Process the input stream if needed
}
}
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}
}
@Test
final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
final HttpPost request = new HttpPost(SAMPLE_POST_URL);
request.setEntity(new StringEntity("in the body of the POST"));
client.execute(request);
}
@Test
final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
final HttpPost request = new HttpPost(SAMPLE_POST_URL);
request.setEntity(new StringEntity("in the body of the POST"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
request.addHeader(new BasicScheme().authenticate(creds, request, null));
client.execute(request);
}
}

View File

@ -1,24 +0,0 @@
package com.baeldung.httpclient;
import java.io.IOException;
import org.apache.http.HttpHeaders;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.jupiter.api.Test;
class HttpClientHeaderV4LiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
@Test
void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws IOException {
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(SAMPLE_URL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
}
}

View File

@ -1,70 +0,0 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
class HttpClientRedirectV4LiveTest {
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@BeforeEach
public final void before() {
instance = HttpClientBuilder.create()
.build();
}
@AfterEach
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
instance = HttpClients.custom()
.disableRedirectHandling()
.build();
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
response = instance.execute(httpGet);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(301));
}
// redirect with POST
@Test
void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
instance = HttpClientBuilder.create()
.build();
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(301));
}
@Test
void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
instance = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
}

View File

@ -1,138 +0,0 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.baeldung.GetRequestMockServer;
class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
private CloseableHttpResponse response;
@AfterEach
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
@Test
void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
final int timeout = 2;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
final HttpGet request = new HttpGet("http://www.github.com");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException {
final int timeout = 2;
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultSocketConfig(config).build();
final HttpGet request = new HttpGet("http://www.github.com");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException {
final int timeout = 5;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
final HttpGet request = new HttpGet("http://www.github.com");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
/**
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
*/
@Test
@Disabled
void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
final int timeout = 3;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
final HttpGet request = new HttpGet("http://www.google.com:81");
assertThrows(ConnectTimeoutException.class, () -> {
client.execute(request);
});
}
@Test
final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() {
final RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5)
.setConnectTimeout(5)
.setSocketTimeout(2)
.build();
final CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.build();
final HttpGet request = new HttpGet("http://www.github.com");
assertThrows(ConnectTimeoutException.class, () -> {
response = client.execute(request);
});
}
@Test
void whenSecuredRestApiIsConsumed_then200OK() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
int timeout = 20; // seconds
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
HttpGet getMethod = new HttpGet(simplePathUrl);
getMethod.setConfig(requestConfig);
int hardTimeout = 5; // seconds
TimerTask task = new TimerTask() {
@Override
public void run() {
getMethod.abort();
}
};
new Timer(true).schedule(task, hardTimeout * 1000);
HttpResponse response = httpClient.execute(getMethod);
System.out.println("HTTP Status of response: " + response.getStatusLine().getStatusCode());
}
}

View File

@ -1,111 +0,0 @@
package com.baeldung.httpclient;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.junit.jupiter.api.Test;
class HttpsClientV4SslLiveTest {
// "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local
// "https://mms.nw.ru/" // hosted
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
// tests
@Test
void whenHttpsUrlIsConsumed_thenException() {
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
assertThrows(SSLHandshakeException.class, () -> {
final CloseableHttpClient httpClient = HttpClientBuilder
.create()
.build();
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
});
}
@Test
void whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
void using_builder_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(hostnameVerifier)
.setSSLSocketFactory(sslsf)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true)
.build();
final CloseableHttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import java.io.IOException;
public final class ResponseUtil {
private ResponseUtil() {
}
public static void closeResponse(CloseableHttpResponse response) throws IOException {
if (response == null) {
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
entity.getContent().close();
}
} finally {
response.close();
}
}
}

View File

@ -1,173 +0,0 @@
package com.baeldung.httpclient.advancedconfig;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.jupiter.api.Assertions.assertEquals;
class HttpClientAdvancedConfigurationIntegrationTest {
public WireMockServer serviceMock;
public WireMockServer proxyMock;
@BeforeEach
public void before () {
serviceMock = new WireMockServer(8089);
serviceMock.start();
proxyMock = new WireMockServer(8090);
proxyMock.start();
}
@AfterEach
public void after () {
serviceMock.stop();
proxyMock.stop();
}
@Test
void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
//given
String userAgent = "BaeldungAgent/1.0";
serviceMock.stubFor(get(urlEqualTo("/detail"))
.withHeader("User-Agent", equalTo(userAgent))
.willReturn(aResponse()
.withStatus(200)));
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8089/detail");
httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent);
//when
HttpResponse response = httpClient.execute(httpGet);
//then
assertEquals(200, response.getStatusLine().getStatusCode());
}
@Test
void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
//given
String xmlBody = "<xml><id>1</id></xml>";
serviceMock.stubFor(post(urlEqualTo("/person"))
.withHeader("Content-Type", equalTo("application/xml"))
.withRequestBody(equalTo(xmlBody))
.willReturn(aResponse()
.withStatus(200)));
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8089/person");
httpPost.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlBody);
httpPost.setEntity(xmlEntity);
//when
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(200, response.getStatusLine().getStatusCode());
}
@Test
void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
//given
proxyMock.stubFor(get(urlMatching(".*"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089")));
serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(200, response.getStatusLine().getStatusCode());
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@Test
void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
//given
proxyMock.stubFor(get(urlMatching("/private"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089")));
serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
// Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.setDefaultCredentialsProvider(credentialsProvider)
.build();
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(200, response.getStatusLine().getStatusCode());
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
}

View File

@ -1,138 +0,0 @@
package com.baeldung.httpclient.expandurl;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class HttpClientExpandUrlLiveTest {
private CloseableHttpClient client;
@BeforeEach
public final void beforeEach() {
client = HttpClientBuilder.create().disableRedirectHandling().build();
}
@Test
final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
final String expectedResult = "https://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
assertThat(actualResult, equalTo(expectedResult));
}
@Test
final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
final String expectedResult = "https://www.baeldung.com/rest-versioning";
final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult));
}
private String expand(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
return newUrl;
}
final String expandSafe(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
return newUrl;
}
private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
HttpHead request = null;
HttpEntity httpEntity = null;
InputStream entityContentStream = null;
try {
request = new HttpHead(url);
final HttpResponse httpResponse = client.execute(request);
httpEntity = httpResponse.getEntity();
entityContentStream = httpEntity.getContent();
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<>(statusCode, url);
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
return new ImmutablePair<>(statusCode, newUrl);
} catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<>(500, url);
} finally {
if (request != null) {
request.releaseConnection();
}
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
private String expandSingleLevel(final String url) throws IOException {
HttpHead request = null;
try {
request = new HttpHead(url);
final HttpResponse httpResponse = client.execute(request);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) {
return url;
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
return headers[0].getValue();
} catch (final IllegalArgumentException uriEx) {
return url;
} finally {
if (request != null) {
request.releaseConnection();
}
}
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.httpclient.httpclient;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import com.baeldung.GetRequestMockServer;
class ApacheHttpClientUnitTest extends GetRequestMockServer {
@Test
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGet = new HttpGet(simplePathUrl);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
}
}
}
}

View File

@ -1,352 +0,0 @@
package com.baeldung.httpclient.httpclient.conn;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class HttpClientConnectionManagementLiveTest {
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
@Test
final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException {
try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) {
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
final ConnectionRequest connRequest = connManager.requestConnection(route, null);
assertNotNull(connRequest.get(1000, TimeUnit.SECONDS));
}
}
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
@Test
final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
client.execute(new HttpGet("https://www.baeldung.com"));
assertEquals(1, poolingConnManager.getTotalStats()
.getLeased());
}
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
@Test
final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client1 = HttpClients.custom()
.setConnectionManager(connManager)
.build();
CloseableHttpClient client2 = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertEquals(0, connManager.getTotalStats()
.getLeased());
}
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
@Test
final void whenIncreasingConnectionPool_thenNoEceptions() {
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
HttpHost host = new HttpHost("www.baeldung.com", 80);
connManager.setMaxPerRoute(new HttpRoute(host), 5);
}
}
// Example 4.2. Using Threads to Execute Connections
@Test
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get);
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
}
// Example 5.1. A Custom Keep Alive Strategy
@Test
final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if ((value != null) && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
if ("localhost".equalsIgnoreCase(target.getHostName())) {
return 10 * 1000;
} else {
return 5 * 1000;
}
}
};
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setKeepAliveStrategy(myStrategy)
.setConnectionManager(connManager)
.build();
}
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
@Test
final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
HttpClientContext context = HttpClientContext.create();
// low level
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
ConnectionRequest connRequest = basicConnManager.requestConnection(route, null);
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
basicConnManager.connect(conn, route, 1000, context);
basicConnManager.routeComplete(conn, route, context);
HttpRequestExecutor exeRequest = new HttpRequestExecutor();
context.setTargetHost((new HttpHost("www.baeldung.com", 80)));
HttpGet get = new HttpGet("http://www.baeldung.com");
exeRequest.execute(get, conn, context);
basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
// high level
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(basicConnManager)
.build();
client.execute(get);
}
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
@Test
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
HttpGet get = new HttpGet("http://echo.200please.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(5);
connManager.setMaxTotal(5);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new MultiHttpClientConnThread(client, get, connManager);
}
for (MultiHttpClientConnThread thread : threads) {
thread.start();
}
for (MultiHttpClientConnThread thread : threads) {
thread.join(1000);
}
}
// Example 7.1. Setting Socket Timeout to 5 Seconds
@Test
final void whenConfiguringTimeOut_thenNoExceptions() {
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
connManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom()
.setSoTimeout(5000)
.build());
assertEquals(5000, connManager.getSocketConfig(route.getTargetHost())
.getSoTimeout());
}
}
// Example 8.1. Setting the HttpClient to Check for Stale Connections
@Test
final void whenHttpClientChecksStaleConns_thenNoExceptions() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setStaleConnectionCheckEnabled(true)
.build())
.setConnectionManager(connManager)
.build();
}
// Example 8.2. Using a Stale Connection Monitor Thread
@Test
final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setConnectionManager(connManager)
.build();
IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(connManager);
staleMonitor.start();
staleMonitor.join(1000);
}
// Example 9.1. Closing Connection and Releasing Resources
@Test
final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
final HttpGet get = new HttpGet("http://google.com");
CloseableHttpResponse response = client.execute(get);
EntityUtils.consume(response.getEntity());
response.close();
client.close();
connManager.close();
connManager.shutdown();
assertThrows(IllegalStateException.class, () -> {
client.execute(get);
});
}
@Test
// Example 3.2. TESTER VERSION
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
final CloseableHttpClient client1 = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final CloseableHttpClient client2 = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager);
thread1.start();
thread2.start();
thread1.join();
thread2.join(1000);
assertEquals(2, poolingConnManager.getTotalStats()
.getLeased());
}
@Test
// Example 4.2 Tester Version
final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
thread1.start();
thread2.start();
thread3.start();
thread1.join(10000);
thread2.join(10000);
thread3.join(10000);
}
@Test
// 6.2 TESTER VERSION
final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
poolingConnManager.setDefaultMaxPerRoute(5);
poolingConnManager.setMaxTotal(5);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
int countConnMade = 0;
for (int i = 0; i < threads.length; i++) {
threads[i] = new MultiHttpClientConnThread(client, new HttpGet("http://www.baeldung.com/"), poolingConnManager);
}
for (final MultiHttpClientConnThread thread : threads) {
thread.start();
}
for (final MultiHttpClientConnThread thread : threads) {
thread.join(10000);
countConnMade++;
if (countConnMade == 0) {
assertEquals(5, thread.getLeasedConn());
}
}
}
@Test
@Disabled("Very Long Running")
// 8.2 TESTER VERSION
final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);
final HttpGet get = new HttpGet("http://google.com");
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
staleMonitor.start();
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
assertEquals(1, poolingConnManager.getTotalStats()
.getAvailable());
thread3.join(32000);
assertEquals(0, poolingConnManager.getTotalStats()
.getAvailable());
}
}

View File

@ -1,41 +0,0 @@
package com.baeldung.httpclient.httpclient.conn;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
// API
@Override
public final void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(1000);
connMgr.closeExpiredConnections();
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (final InterruptedException ex) {
shutdown();
}
}
private void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}

View File

@ -1,68 +0,0 @@
package com.baeldung.httpclient.httpclient.conn;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MultiHttpClientConnThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final CloseableHttpClient client;
private final HttpGet get;
private PoolingHttpClientConnectionManager connManager;
private int leasedConn;
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
this.client = client;
this.get = get;
this.connManager = connManager;
leasedConn = 0;
}
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
this.client = client;
this.get = get;
}
// API
final int getLeasedConn() {
return leasedConn;
}
//
@Override
public final void run() {
try {
logger.debug("Thread Running: " + getName());
logger.debug("Thread Running: " + getName());
if (connManager != null) {
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
}
final HttpResponse response = client.execute(get);
if (connManager != null) {
leasedConn = connManager.getTotalStats().getLeased();
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
}
EntityUtils.consume(response.getEntity());
} catch (final IOException ex) {
logger.error("", ex);
}
}
}

View File

@ -1,45 +0,0 @@
package com.baeldung.httpclient.httpclient.conn;
import java.io.IOException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
public class TesterVersion_MultiHttpClientConnThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final CloseableHttpClient client;
private final HttpGet get;
private PoolingHttpClientConnectionManager connManager;
TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
this.client = client;
this.get = get;
this.connManager = Preconditions.checkNotNull(connManager);
}
//
@Override
public final void run() {
try {
logger.debug("Thread Running: " + getName());
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
client.execute(get);
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
} catch (final IOException ex) {
logger.error("", ex);
}
}
}

View File

@ -1,29 +0,0 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
class ApacheHttpClientUnitTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
void whenUseApacheHttpClient_thenCorrect() throws IOException {
HttpGet request = new HttpGet(DUMMY_URL);
try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
logger.debug("Response -> {}", EntityUtils.toString(entity));
}
}
}

View File

@ -1,168 +0,0 @@
package com.baeldung.httpclient.retry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Objects;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ApacheHttpClientRetryLiveTest {
private Integer requestCounter;
private CloseableHttpClient httpClient;
@BeforeEach
void setUp() {
requestCounter = 0;
}
@AfterEach
void tearDown() throws IOException {
if (httpClient != null) {
httpClient.close();
}
}
private void createDefaultApacheHttpClient() {
this.httpClient = HttpClientBuilder
.create()
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> {
requestCounter++;
}).build();
}
private void createFailingHttpClient() {
this.httpClient = HttpClientBuilder
.create()
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
.addInterceptorLast((HttpResponseInterceptor) (httpResponse, httpContext) -> {
throw new IOException();
})
.build();
}
private void createHttpClientWithRetryHandler() {
this.httpClient = HttpClientBuilder
.create()
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
.addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
.setRetryHandler(new DefaultHttpRequestRetryHandler(6, true))
.build();
}
private void createHttpClientWithCustomRetryHandler() {
this.httpClient = HttpClientBuilder
.create()
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
.addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
.setRetryHandler((exception, executionCount, context) -> {
if (executionCount < 5 && Objects.equals("GET", ((HttpClientContext) context).getRequest().getRequestLine().getMethod())) {
return true;
} else {
return false;
}
})
.build();
}
private void createHttpClientWithRetriesDisabled() {
this.httpClient = HttpClientBuilder
.create()
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
.addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
.disableAutomaticRetries()
.build();
}
@Test
void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
createFailingHttpClient();
assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200")));
assertThat(requestCounter).isEqualTo(4);
}
@Test
void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
createDefaultApacheHttpClient();
HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1"));
assertThrows(UnknownHostException.class, () -> httpClient.execute(request));
assertThat(requestCounter).isEqualTo(1);
}
@Test
void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
createDefaultApacheHttpClient();
HttpGet request = new HttpGet(URI.create("https://httpstat.us/500"));
CloseableHttpResponse response = assertDoesNotThrow(() -> httpClient.execute(request));
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(500);
assertThat(requestCounter).isEqualTo(1);
response.close();
}
@Test
void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
createFailingHttpClient();
HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500"));
assertThrows(IOException.class, () -> httpClient.execute(request));
assertThat(requestCounter).isEqualTo(1);
}
@Test
void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
createFailingHttpClient();
HttpPut request = new HttpPut(URI.create("https://httpstat.us/500"));
assertThrows(IOException.class, () -> httpClient.execute(request));
assertThat(requestCounter).isEqualTo(1);
}
@Test
void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
createHttpClientWithRetryHandler();
HttpPost request = new HttpPost(URI.create("https://httpstat.us/200"));
assertThrows(IOException.class, () -> httpClient.execute(request));
assertThat(requestCounter).isEqualTo(7);
}
@Test
void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
createHttpClientWithCustomRetryHandler();
HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200"));
assertThrows(IOException.class, () -> httpClient.execute(request));
assertThat(requestCounter).isEqualTo(5);
}
@Test
void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
createHttpClientWithRetriesDisabled();
HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));
assertThrows(IOException.class, () -> httpClient.execute(request));
assertThat(requestCounter).isEqualTo(1);
}
}

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1 +0,0 @@
hello world

View File

@ -17,4 +17,22 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Apache HttpClient Do Not Follow Redirects](https://www.baeldung.com/httpclient-stop-follow-redirect) - [Apache HttpClient Do Not Follow Redirects](https://www.baeldung.com/httpclient-stop-follow-redirect)
- [Custom User-Agent in Apache HttpClient](https://www.baeldung.com/httpclient-user-agent-header) - [Custom User-Agent in Apache HttpClient](https://www.baeldung.com/httpclient-user-agent-header)
- [Apache HttpClient Connection Management](https://www.baeldung.com/httpclient-connection-management) - [Apache HttpClient Connection Management](https://www.baeldung.com/httpclient-connection-management)
- More articles: [[next -->]](../apache-httpclient-2) - [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/apache-httpclient-tls)
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- [Apache HttpClient Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl)
- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout)
- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- [Retrying Requests using Apache HttpClient](https://www.baeldung.com/java-retrying-requests-using-apache-httpclient)
- [Apache HttpClient Follow Redirects for POST](https://www.baeldung.com/httpclient-redirect-on-http-post)
### Running the Tests
To run the live tests, use the command: mvn clean install -Plive
This will start an embedded Jetty server on port 8082 using the Cargo plugin configured in the pom.xml file,
for the live Maven profile

View File

@ -1,4 +1,4 @@
package com.baeldung.tlsversion; package com.ossez.tlsversion;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient; package com.ossez.httpclient;
import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.exactly;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient; package com.ossez.httpclient;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
@ -97,7 +97,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
@Test @Test
void whenUseProxyWithHttpClient_thenCorrect() throws Exception { void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort); final HttpHost proxy = new HttpHost("127.0.0.1", serverPort);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom() final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setRoutePlanner(routePlanner) .setRoutePlanner(routePlanner)

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient; package com.ossez.httpclient;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient; package com.ossez.httpclient;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient; package com.ossez.httpclient;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient; package com.ossez.httpclient;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.advancedconfig; package com.ossez.httpclient.advancedconfig;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.containing;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.conn; package com.ossez.httpclient.conn;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.conn; package com.ossez.httpclient.conn;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.conn; package com.ossez.httpclient.conn;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.cookies; package com.ossez.httpclient.cookies;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.expandUrl; package com.ossez.httpclient.expandUrl;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.httpclient; package com.ossez.httpclient.httpclient;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.httpclient; package com.ossez.httpclient.httpclient;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.httpclient; package com.ossez.httpclient.httpclient;
import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.HttpStatus;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.httpclient; package com.ossez.httpclient.httpclient;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.readresponsebodystring; package com.ossez.httpclient.readresponsebodystring;
import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler; import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.readresponsebodystring; package com.ossez.httpclient.readresponsebodystring;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.httpclient.readresponsebodystring; package com.ossez.httpclient.readresponsebodystring;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;