diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index c39983564f..eea056477c 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -1,7 +1,7 @@ + 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"> 4.0.0 httpclient-simple 0.1-SNAPSHOT @@ -10,90 +10,61 @@ com.baeldung - parent-spring-5 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-boot-3 - - org.springframework.security - spring-security-web - ${spring-security.version} + org.springframework.boot + spring-boot-starter - org.springframework.security - spring-security-config - ${spring-security.version} - - - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - + org.springframework.boot + spring-boot-starter-security - org.springframework - spring-context - ${spring.version} + org.springframework.boot + spring-boot-starter-jdbc - org.springframework - spring-jdbc - ${spring.version} + org.springframework.boot + spring-boot-starter-aop - org.springframework - spring-beans - ${spring.version} + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-aop - ${spring.version} + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.0 - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-oxm - ${spring.version} + com.sun.xml.bind + jaxb-impl + 4.0.0 + runtime + com.fasterxml.jackson.core jackson-databind ${jackson.version} + - org.apache.httpcomponents - httpcore - ${httpcore.version} + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.httpcomponents.client5 + httpclient5 + ${httpclient5.version} commons-logging @@ -112,7 +83,6 @@ - org.apache.httpcomponents.client5 httpclient5-fluent @@ -124,67 +94,11 @@ - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - fluent-hc - ${httpclient.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents.client5 - httpclient5 - ${httpclient5.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - httpmime - ${httpclient.version} - commons-codec commons-codec ${commons-codec.version} - - org.apache.httpcomponents - httpasyncclient - ${httpasyncclient.version} - - - commons-logging - commons-logging - - - com.github.tomakehurst wiremock @@ -210,13 +124,6 @@ guava ${guava.version} - - - org.springframework - spring-test - ${spring.version} - test - @@ -231,26 +138,13 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} + 3.3.2 - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} + org.springframework.boot + spring-boot-maven-plugin - true - - jetty8x - embedded - - - - - - - 8082 - - + true @@ -263,7 +157,7 @@ org.codehaus.cargo - cargo-maven2-plugin + cargo-maven3-plugin start-server @@ -310,13 +204,11 @@ + 17 1.10 - 4.1.4 2.5.1 - 4.4.11 - 4.5.8 5.2 5.2 diff --git a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java index cafd8cfb7b..487794cc7f 100644 --- a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -3,8 +3,8 @@ package com.baeldung.basic; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; diff --git a/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java index 81f82a2c1c..7a0599cd49 100644 --- a/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ b/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -2,13 +2,13 @@ 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.apache.hc.core5.http.HttpHost; +import org.apache.hc.client5.http.auth.AuthCache; +import org.apache.hc.client5.http.impl.auth.BasicAuthCache; +import org.apache.hc.client5.http.impl.auth.BasicScheme; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.HttpContext; import org.springframework.http.HttpMethod; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -21,6 +21,7 @@ public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpCompone this.host = host; } + @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return createHttpContext(); } diff --git a/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java b/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java index aac4f8cebd..fafaae0157 100644 --- a/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java +++ b/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java @@ -1,6 +1,6 @@ package com.baeldung.client; -import org.apache.http.HttpHost; +import org.apache.hc.core5.http.HttpHost; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; @@ -35,7 +35,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ @Override public void afterPropertiesSet() { - HttpHost host = new HttpHost("localhost", 8082, "http"); + HttpHost host = new HttpHost("http", "localhost", 8082); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass")); diff --git a/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java b/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java index 6bb12610fa..a9509ddafa 100644 --- a/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java +++ b/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java @@ -2,10 +2,10 @@ 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 jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import java.io.IOException; public class CustomFilter extends GenericFilterBean { diff --git a/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java index fb597e46c8..859b900170 100644 --- a/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ b/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -7,41 +7,38 @@ 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.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 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 extends WebSecurityConfigurerAdapter { +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"); + .inMemoryAuthentication() + .withUser("user1") + .password(passwordEncoder().encode("user1Pass")) + .authorities("ROLE_USER"); } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/securityNone") - .permitAll() - .anyRequest() - .authenticated() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint); + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + http.authorizeHttpRequests((authorize) -> authorize.anyRequest() + .authenticated()) + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + return http.build(); } - + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); diff --git a/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java index 7dc53e3e1e..d53aa5bdfe 100644 --- a/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -2,9 +2,9 @@ package com.baeldung.security; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; diff --git a/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java index 1ae89adb89..615982fae4 100644 --- a/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java +++ b/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java @@ -2,8 +2,8 @@ package com.baeldung.security; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; diff --git a/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java b/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java index eb139b0ec1..1bb7476669 100644 --- a/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java +++ b/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java @@ -2,7 +2,7 @@ package com.baeldung.web.dto; import java.io.Serializable; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Bar implements Serializable { diff --git a/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java b/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java index 23cfab132d..f904be0ad9 100644 --- a/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java +++ b/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java @@ -2,7 +2,7 @@ package com.baeldung.web.dto; import java.io.Serializable; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Foo implements Serializable { diff --git a/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java index 78e9813f06..1c7e766a72 100644 --- a/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java @@ -1,25 +1,23 @@ package com.baeldung.client; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import com.baeldung.client.spring.ClientConfig; +import static org.hamcrest.Matchers.is; +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 com.baeldung.web.dto.Foo; -import org.junit.Test; -import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; + import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ClientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ClientLiveTest { +class ClientLiveTest { @Autowired private RestTemplate secureRestTemplate; @@ -27,21 +25,24 @@ public class ClientLiveTest { // tests @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { + void whenContextIsBootstrapped_thenNoExceptions() { // } @Test - public final void whenSecuredRestApiIsConsumed_then200OK() { + void whenSecuredRestApiIsConsumed_then200OK() { final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/httpclient-simple/api/foos/1", HttpMethod.GET, null, Foo.class); assertThat(responseEntity.getStatusCode().value(), is(200)); } - @Test(expected = ResourceAccessException.class) - public final void whenHttpsUrlIsConsumed_thenException() { + @Test + void whenHttpsUrlIsConsumed_thenException() { final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1"; - final ResponseEntity response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode().value(), equalTo(200)); + assertThrows(ResourceAccessException.class, () -> { + final ResponseEntity response = new RestTemplate() + .exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + }); } } diff --git a/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java b/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java index d133bc376c..efa0695aaf 100644 --- a/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java @@ -1,112 +1,78 @@ package com.baeldung.client; -import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +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.SSLPeerUnverifiedException; -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.scheme.Scheme; -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.SSLSocketFactory; -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.Ignore; -import org.junit.Test; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager; +import org.apache.hc.client5.http.socket.ConnectionSocketFactory; +import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.config.Registry; +import org.apache.hc.core5.http.config.RegistryBuilder; +import org.apache.hc.core5.ssl.SSLContexts; +import org.apache.hc.core5.ssl.TrustStrategy; +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.ResourceAccessException; import org.springframework.web.client.RestTemplate; +import com.baeldung.handler.CustomHttpClientResponseHandler; + + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build * */ -public class RestClientLiveManualTest { +class RestClientLiveManualTest { final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1"; - // tests - // old httpClient will throw UnsupportedOperationException - @Ignore - @Test - public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException { - final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient(); - - final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; - - final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER); - httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf)); - - final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode().value(), equalTo(200)); - } - // new httpClient : 4.4 and above @Test - public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException { + void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() 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 socketFactoryRegistry = RegistryBuilder. create() - .register("https", sslsf) - .register("http", new PlainConnectionSocketFactory()) - .build(); + .register("https", sslsf) + .register("http", new PlainConnectionSocketFactory()) + .build(); final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); final CloseableHttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(sslsf) - .setConnectionManager(connectionManager) - .build(); + .setConnectionManager(connectionManager) + .build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); assertThat(response.getStatusCode().value(), equalTo(200)); } - @Test - public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, 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 - public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - requestFactory.setHttpClient(httpClient); - - final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode().value(), equalTo(200)); - } - - @Test(expected = SSLPeerUnverifiedException.class) - public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { - CloseableHttpClient httpClient = HttpClients.createDefault(); + void whenHttpsUrlIsConsumed_thenException() { String urlOverHttps = "https://localhost:8082/httpclient-simple"; HttpGet getMethod = new HttpGet(urlOverHttps); - HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThrows(SSLPeerUnverifiedException.class, () -> { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler()); + assertThat(response.getCode(), equalTo(200)); + }); } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java index 44262851fd..616b6470af 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java @@ -1,100 +1,76 @@ package com.baeldung.httpclient; import com.google.common.collect.Lists; -import org.apache.http.Header; -import org.apache.http.HttpHeaders; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -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.BasicHeader; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +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.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.message.BasicHeader; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.util.List; -public class HttpClientHeadersLiveTest { +class HttpClientHeadersLiveTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String SAMPLE_URL = "http://www.github.com"; - private CloseableHttpClient client; - - private CloseableHttpResponse response; - - @Before - public final void before() { - client = HttpClientBuilder.create().build(); - } - - @After - public final void after() throws IllegalStateException, IOException { - ResponseUtil.closeResponse(response); - } - - // tests - headers - deprecated - @Test - public final void givenNewApi_whenClientUsesCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build(); - + void whenClientUsesCustomUserAgent_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); - response = client.execute(request); + + try (CloseableHttpClient client = HttpClients.custom() + .setUserAgent("Mozilla/5.0 Firefox/26.0") + .build()) { + + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.info("Response -> {}", response); + } } - // tests - headers - user agent - @Test - public final void givenConfigOnRequest_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().build(); + void whenRequestHasCustomUserAgent_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0"); - response = client.execute(request); + + try (CloseableHttpClient client = HttpClients.createDefault()) { + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.info("Response -> {}", response); + } } @Test - public final void givenConfigOnClient_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build(); - response = client.execute(new HttpGet(SAMPLE_URL)); - } - - // tests - headers - content type - - @Test - public final void givenUsingNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().build(); + void whenRequestHasCustomContentType_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - response = client.execute(request); + + try (CloseableHttpClient client = HttpClients.createDefault()) { + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.debug("Response -> {}", response); + } } @Test - public final void givenRequestBuildWithBuilderWithNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient client2 = HttpClients.custom().build(); + void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); - request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - response = client2.execute(request); - } - - @Test - public final void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().build(); - final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).setHeader(HttpHeaders.CONTENT_TYPE, "application/json").build(); - response = client.execute(request); - } - - @Test - public final void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { final Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); final List
headers = Lists.newArrayList(header); - client = HttpClients.custom().setDefaultHeaders(headers).build(); - final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build(); - response = client.execute(request); - } + + try (CloseableHttpClient client = HttpClients.custom() + .setDefaultHeaders(headers) + .build()) { + + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.debug("Response -> {}", response); + } + } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java index f56a6863a3..ef662e1bd8 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java @@ -1,7 +1,8 @@ package com.baeldung.httpclient; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; + import java.io.IOException; import java.net.URI; @@ -14,28 +15,25 @@ import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.net.URIBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import com.baeldung.handler.CustomHttpClientResponseHandler; -public class HttpClientParamsLiveTest { +class HttpClientParamsLiveTest { - private CloseableHttpClient client; - - private CloseableHttpResponse response; private List nameValuePairs; - @Before + @BeforeEach public void setUp() { - client = HttpClientBuilder.create() - .build(); nameValuePairs = new ArrayList<>(); NameValuePair param1NameValuePair = new BasicNameValuePair("param1", "value1"); NameValuePair param2NameValuePair = new BasicNameValuePair("param2", "value2"); @@ -44,63 +42,83 @@ public class HttpClientParamsLiveTest { } @Test - public void givenStringNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenStringNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpGet httpGet = new HttpGet("https://postman-echo.com/get"); URI uri = new URIBuilder(httpGet.getUri()).addParameter("param1", "value1") .addParameter("param2", "value2") .build(); httpGet.setUri(uri); - response = client.execute(httpGet); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpGet, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenStringNameValuePairParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenStringNameValuePairParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpPost httpPost = new HttpPost("https://postman-echo.com/post"); URI uri = new URIBuilder(httpPost.getUri()).addParameter("param1", "value1") .addParameter("param2", "value2") .build(); httpPost.setUri(uri); - response = client.execute(httpPost); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpGet httpGet = new HttpGet("https://postman-echo.com/get"); URI uri = new URIBuilder(httpGet.getUri()).addParameters(nameValuePairs) .build(); httpGet.setUri(uri); - response = client.execute(httpGet); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpGet, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenNameValuePairsParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenNameValuePairsParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpPost httpPost = new HttpPost("https://postman-echo.com/post"); URI uri = new URIBuilder(httpPost.getUri()).addParameters(nameValuePairs) .build(); httpPost.setUri(uri); - response = client.execute(httpPost); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenUrlEncodedEntityParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenUrlEncodedEntityParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpPost httpPost = new HttpPost("https://postman-echo.com/post"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8)); - response = client.execute(httpPost); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java index ab80d5665f..f3d0a1c27f 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java @@ -3,7 +3,6 @@ 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 static org.mockito.Mockito.when; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java index 24ceab0069..54633ba932 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,7 +1,6 @@ package com.baeldung.httpclient; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.security.GeneralSecurityException; @@ -9,73 +8,50 @@ 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.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.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.ssl.SSLContexts; -import org.junit.Test; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.io.HttpClientConnectionManager; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.ssl.SSLContextBuilder; +import org.apache.hc.core5.ssl.SSLContexts; +import org.apache.hc.core5.ssl.TrustStrategy; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import com.baeldung.handler.CustomHttpClientResponseHandler; /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build * */ -public class HttpsClientSslLiveTest { +class HttpsClientSslLiveTest { // "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(expected = SSLHandshakeException.class) - public final void whenHttpsUrlIsConsumed_thenException() throws IOException { - final CloseableHttpClient httpClient = HttpClientBuilder.create() - .build(); - + @Test + void whenHttpsUrlIsConsumed_thenException() { final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); + + assertThrows(SSLHandshakeException.class, () -> { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler()); + MatcherAssert.assertThat(response.getCode(), Matchers.equalTo(200)); + }); + } @Test - public final void givenHttpClientPre4_3_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); - Registry socketFactoryRegistry = RegistryBuilder. create().register("https", sslsf).build(); - PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - - final CloseableHttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(sslsf) - .setConnectionManager(clientConnectionManager) - .build(); - - final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); - - httpClient.close(); - } - - @Test - public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { + void whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) @@ -83,55 +59,45 @@ public class HttpsClientSslLiveTest { final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); - final CloseableHttpClient httpClient = HttpClients.custom() + final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(sslsf) .build(); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); + try (CloseableHttpClient client = HttpClients.custom() + .setConnectionManager(cm) + .build(); - httpClient.close(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(getMethod, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + MatcherAssert.assertThat(statusCode, Matchers.equalTo(HttpStatus.SC_OK)); + } } @Test - public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { + void usingBuilder_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) + final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(sslsf) .build(); - // new - final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); - httpClient.close(); - - } - - @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { - final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true) + try (CloseableHttpClient client = HttpClients.custom() + .setConnectionManager(cm) .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"); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(getMethod, new CustomHttpClientResponseHandler())) { - final HttpResponse response = client.execute(httpGet); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); + final int statusCode = response.getCode(); + MatcherAssert.assertThat(statusCode, Matchers.equalTo(HttpStatus.SC_OK)); + } } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java index e05017ccdd..b850f2e8ba 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java @@ -19,12 +19,12 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; -public class HttpClientBasicLiveTest { +class HttpClientBasicLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @Test - public final void whenExecutingBasicGetRequest_thenNoExceptions() throws IOException { + void whenExecutingBasicGetRequest_thenNoExceptions() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); @@ -35,7 +35,7 @@ public class HttpClientBasicLiveTest { } @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { + void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); @@ -48,7 +48,7 @@ public class HttpClientBasicLiveTest { @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws IOException { + void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); @@ -63,7 +63,7 @@ public class HttpClientBasicLiveTest { @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws IOException, ParseException { + void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws IOException, ParseException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); diff --git a/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java b/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java deleted file mode 100644 index c864349e02..0000000000 --- a/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.test; - -import com.baeldung.client.ClientLiveTest; -import com.baeldung.client.RestClientLiveManualTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ -// @formatter:off - RestClientLiveManualTest.class - ,ClientLiveTest.class -}) // -public class LiveTestSuite { - -} diff --git a/httpclient4/.gitignore b/httpclient4/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/httpclient4/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/httpclient4/README.md b/httpclient4/README.md new file mode 100644 index 0000000000..08e04c511d --- /dev/null +++ b/httpclient4/README.md @@ -0,0 +1,13 @@ +## Apache HttpClient + +This module contains articles about Apache HttpClient 4.5 + +### Relevant Articles + +- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl) +- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout) + +### 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 \ No newline at end of file diff --git a/httpclient4/pom.xml b/httpclient4/pom.xml new file mode 100644 index 0000000000..8f896283b3 --- /dev/null +++ b/httpclient4/pom.xml @@ -0,0 +1,291 @@ + + + 4.0.0 + httpclient4 + 0.1-SNAPSHOT + httpclient4 + war + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + + org.springframework.security + spring-security-web + ${spring-security.version} + + + org.springframework.security + spring-security-config + ${spring-security.version} + + + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + org.springframework + spring-oxm + ${spring.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + commons-logging + commons-logging + + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + org.apache.httpcomponents + fluent-hc + ${httpclient.version} + + + commons-logging + commons-logging + + + + + org.apache.httpcomponents + httpmime + ${httpclient.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.apache.httpcomponents + httpasyncclient + ${httpasyncclient.version} + + + commons-logging + commons-logging + + + + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + com.google.guava + guava + ${guava.version} + + + + org.springframework + spring-test + ${spring.version} + test + + + + + httpclient-simple + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + + 1.10 + 4.1.5 + + 2.5.1 + 4.4.16 + 4.5.14 + + 1.6.1 + + + \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java new file mode 100644 index 0000000000..cafd8cfb7b --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -0,0 +1,30 @@ +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(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java new file mode 100644 index 0000000000..81f82a2c1c --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -0,0 +1,39 @@ +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; + } +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java b/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java new file mode 100644 index 0000000000..aac4f8cebd --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java @@ -0,0 +1,44 @@ +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, InitializingBean { + private RestTemplate restTemplate; + + public RestTemplateFactory() { + super(); + } + + // API + + @Override + public RestTemplate getObject() { + return restTemplate; + } + + @Override + public Class 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")); + } + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java b/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java new file mode 100644 index 0000000000..03994b55a5 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java @@ -0,0 +1,16 @@ +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 + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java b/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java new file mode 100644 index 0000000000..6bb12610fa --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java @@ -0,0 +1,18 @@ +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); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java new file mode 100644 index 0000000000..fb597e46c8 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -0,0 +1,49 @@ +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.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("user1") + .password(passwordEncoder().encode("user1Pass")) + .authorities("ROLE_USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/securityNone") + .permitAll() + .anyRequest() + .authenticated() + .and() + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); + + http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..7dc53e3e1e --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -0,0 +1,48 @@ +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; + } +} diff --git a/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000000..1ae89adb89 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,23 @@ +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"); + } + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..4ba9d47f8d --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,16 @@ +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(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java b/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java new file mode 100644 index 0000000000..8d5c1dc7f1 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java @@ -0,0 +1,30 @@ +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> converters) { + converters.add(new MappingJackson2HttpMessageConverter()); + } + + // + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java b/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java new file mode 100644 index 0000000000..02e6af03af --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java @@ -0,0 +1,31 @@ +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(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java b/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..461a5e351a --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java @@ -0,0 +1,33 @@ +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(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java b/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java new file mode 100644 index 0000000000..eb139b0ec1 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java @@ -0,0 +1,14 @@ +package com.baeldung.web.dto; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Bar implements Serializable { + + public Bar() { + super(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java b/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..23cfab132d --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java @@ -0,0 +1,14 @@ +package com.baeldung.web.dto; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Foo implements Serializable { + + public Foo() { + super(); + } + +} diff --git a/httpclient4/src/main/resources/logback.xml b/httpclient4/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/httpclient4/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient4/src/main/resources/webSecurityConfig.xml b/httpclient4/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..2ff9a1de15 --- /dev/null +++ b/httpclient4/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml b/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml new file mode 100644 index 0000000000..1dbff70b83 --- /dev/null +++ b/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/httpclient4/src/main/webapp/WEB-INF/web.xml b/httpclient4/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4b2dd54266 --- /dev/null +++ b/httpclient4/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,43 @@ + + + + Spring Security Custom Application + + + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + + api + org.springframework.web.servlet.DispatcherServlet + 1 + + + api + /api/* + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + \ No newline at end of file diff --git a/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java new file mode 100644 index 0000000000..2785bc5d08 --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java @@ -0,0 +1,99 @@ +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.SSLPeerUnverifiedException; + +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; + + +class ClientLiveTest { + + 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 socketFactoryRegistry = RegistryBuilder. 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 response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { + final HttpGet getMethod = new HttpGet(urlOverHttps); + + 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 response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + void whenHttpsUrlIsConsumed_thenException() { + String urlOverHttps = "https://localhost:8082/httpclient-simple"; + HttpGet getMethod = new HttpGet(urlOverHttps); + + assertThrows(SSLPeerUnverifiedException.class, () -> { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + }); + } +} \ No newline at end of file diff --git a/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java new file mode 100644 index 0000000000..c336e6a068 --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java @@ -0,0 +1,92 @@ +package com.baeldung.client; + +import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; +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
+ * It should only be manually run, not part of the automated build + * */ +public 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 socketFactoryRegistry = RegistryBuilder. 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 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 response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + public 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)); + } +} diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java new file mode 100644 index 0000000000..eef813b3ff --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java @@ -0,0 +1,24 @@ +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); + } +} \ No newline at end of file diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java similarity index 97% rename from httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java rename to httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java index 9bf523590e..4d4dd7be15 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java +++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java @@ -76,7 +76,7 @@ class HttpClientTimeoutV4LiveTest { */ @Test @Disabled - public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { + 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(); diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java new file mode 100644 index 0000000000..6c7bcf9b08 --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java @@ -0,0 +1,111 @@ +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)); + } + +} \ No newline at end of file diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java similarity index 100% rename from httpclient-simple/src/test/java/com/baeldung/httpclient/ResponseUtil.java rename to httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java diff --git a/httpclient4/src/test/resources/.gitignore b/httpclient4/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/httpclient4/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/httpclient4/src/test/resources/test.in b/httpclient4/src/test/resources/test.in new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/httpclient4/src/test/resources/test.in @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/pom.xml b/pom.xml index 05f8326e4c..4016d669a4 100644 --- a/pom.xml +++ b/pom.xml @@ -365,7 +365,7 @@ apache-httpclient - httpclient-simple + httpclient4 jackson-modules @@ -648,7 +648,7 @@ apache-httpclient - httpclient-simple + httpclient4 jackson-modules @@ -976,6 +976,7 @@ akka-modules annotations apache-httpclient + httpclient-simple antlr apache-kafka apache-kafka-2 @@ -1201,6 +1202,7 @@ graphql-modules grpc hazelcast + httpclient-simple hystrix jackson-simple java-blockchain