diff --git a/apache-httpclient-2/.gitignore b/apache-httpclient-2/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/apache-httpclient-2/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.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/apache-httpclient-2/README.md b/apache-httpclient-2/README.md deleted file mode 100644 index 05bebfaacb..0000000000 --- a/apache-httpclient-2/README.md +++ /dev/null @@ -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) diff --git a/apache-httpclient-2/pom.xml b/apache-httpclient-2/pom.xml deleted file mode 100644 index 9e845d2ea5..0000000000 --- a/apache-httpclient-2/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - 4.0.0 - apache-httpclient-2 - 0.1-SNAPSHOT - apache-httpclient-2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.apache.httpcomponents.client5 - httpclient5 - ${httpclient5.version} - - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - test - - - - org.springframework.boot - spring-boot-starter-webflux - ${spring-boot.version} - - - org.mock-server - mockserver-netty - ${mockserver.version} - - - org.mock-server - mockserver-client-java - ${mockserver.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - apache-httpclient-2 - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - - - 5.11.2 - 5.2.1 - 2.1.7.RELEASE - - - \ No newline at end of file diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java deleted file mode 100644 index e06cc165f0..0000000000 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java +++ /dev/null @@ -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); - } - -} diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java deleted file mode 100644 index df71bab983..0000000000 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java +++ /dev/null @@ -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 body = webClient.get().retrieve().bodyToMono(String.class); - String s = body.block(); - System.out.println(s); - } -} diff --git a/apache-httpclient4/.gitignore b/apache-httpclient4/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/apache-httpclient4/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.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/apache-httpclient4/README.md b/apache-httpclient4/README.md deleted file mode 100644 index 0bc4ac8e83..0000000000 --- a/apache-httpclient4/README.md +++ /dev/null @@ -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 diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml deleted file mode 100644 index 89e85fc1b4..0000000000 --- a/apache-httpclient4/pom.xml +++ /dev/null @@ -1,240 +0,0 @@ - - - 4.0.0 - apache-httpclient4 - 0.1-SNAPSHOT - war - apache-httpclient4 - - - 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-oxm.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 - - - - - org.mock-server - mockserver-netty - ${mockserver.version} - - - org.wiremock - wiremock - ${wiremock.version} - test - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - - - javax.servlet - jstl - ${jstl.version} - runtime - - - - org.springframework - spring-test - ${spring.version} - test - - - - - httpclient-simple - - - src/main/resources - true - - - - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - - - - - - - - - - 6.1.4 - - 1.16.0 - 4.1.5 - - 3.3.1 - 4.4.16 - 4.5.14 - 5.11.2 - - - \ No newline at end of file diff --git a/apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java deleted file mode 100644 index cafd8cfb7b..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ /dev/null @@ -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(); - } - -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java deleted file mode 100644 index 81f82a2c1c..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ /dev/null @@ -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; - } -} \ No newline at end of file diff --git a/apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java b/apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java deleted file mode 100644 index aac4f8cebd..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java +++ /dev/null @@ -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, 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/apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java b/apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java deleted file mode 100644 index 03994b55a5..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java +++ /dev/null @@ -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 - -} \ No newline at end of file diff --git a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java deleted file mode 100644 index 6bb12610fa..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java +++ /dev/null @@ -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); - } - -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java deleted file mode 100644 index eaf166a091..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ /dev/null @@ -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(); - } -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java deleted file mode 100644 index 7dc53e3e1e..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java +++ /dev/null @@ -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; - } -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java deleted file mode 100644 index 1ae89adb89..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java +++ /dev/null @@ -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"); - } - -} \ No newline at end of file diff --git a/apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java deleted file mode 100644 index 4ba9d47f8d..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java +++ /dev/null @@ -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(); - } - -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java b/apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java deleted file mode 100644 index 8d5c1dc7f1..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java +++ /dev/null @@ -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> converters) { - converters.add(new MappingJackson2HttpMessageConverter()); - } - - // - -} \ No newline at end of file diff --git a/apache-httpclient4/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java b/apache-httpclient4/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java deleted file mode 100644 index c58763b1c0..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java +++ /dev/null @@ -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); - } - } -} \ No newline at end of file diff --git a/apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java b/apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java deleted file mode 100644 index 02e6af03af..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java +++ /dev/null @@ -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(); - } - -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java b/apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java deleted file mode 100644 index 461a5e351a..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java +++ /dev/null @@ -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(); - } - -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java b/apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java deleted file mode 100644 index eb139b0ec1..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java +++ /dev/null @@ -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(); - } - -} diff --git a/apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java b/apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java deleted file mode 100644 index 23cfab132d..0000000000 --- a/apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java +++ /dev/null @@ -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(); - } - -} diff --git a/apache-httpclient4/src/main/resources/logback.xml b/apache-httpclient4/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/apache-httpclient4/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/apache-httpclient4/src/main/resources/webSecurityConfig.xml b/apache-httpclient4/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index 2ff9a1de15..0000000000 --- a/apache-httpclient4/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml b/apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml deleted file mode 100644 index 1dbff70b83..0000000000 --- a/apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/apache-httpclient4/src/main/webapp/WEB-INF/web.xml b/apache-httpclient4/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 4b2dd54266..0000000000 --- a/apache-httpclient4/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - 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/apache-httpclient4/src/test/java/com/baeldung/GetRequestMockServer.java b/apache-httpclient4/src/test/java/com/baeldung/GetRequestMockServer.java deleted file mode 100644 index 52f1baa30d..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/GetRequestMockServer.java +++ /dev/null @@ -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(); - } - } - -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java deleted file mode 100644 index 9d1052b7b3..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java +++ /dev/null @@ -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 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(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 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)); - }); - } - - -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/client/HttpClientSandboxLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/HttpClientSandboxLiveTest.java deleted file mode 100644 index c15d8953f2..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/client/HttpClientSandboxLiveTest.java +++ /dev/null @@ -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); - } -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java deleted file mode 100644 index 98c6a0b4a7..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java +++ /dev/null @@ -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
- * 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 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 - 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/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java deleted file mode 100644 index 0b0d7104d7..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java +++ /dev/null @@ -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(); - } -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java deleted file mode 100644 index 90b64092e0..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java +++ /dev/null @@ -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 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 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 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 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 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 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()); - } - } - - } -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java deleted file mode 100644 index 6a8a66e87b..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java +++ /dev/null @@ -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(); - } - } -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java deleted file mode 100644 index ba77a5c7dd..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java +++ /dev/null @@ -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 params = new ArrayList(); - 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); - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java deleted file mode 100644 index eef813b3ff..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java +++ /dev/null @@ -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); - } -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java deleted file mode 100644 index a3f9f3eb47..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java +++ /dev/null @@ -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)); - } - -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java deleted file mode 100644 index 5b3ced8b98..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java +++ /dev/null @@ -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()); - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java deleted file mode 100644 index 6c7bcf9b08..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java +++ /dev/null @@ -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)); - } - -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java deleted file mode 100644 index e9ea08a723..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java +++ /dev/null @@ -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(); - } - } -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java deleted file mode 100644 index 714c01192e..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ /dev/null @@ -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 = "1"; - 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"))); - } - - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java deleted file mode 100644 index c1b04c6728..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java +++ /dev/null @@ -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 alreadyVisited = Lists.newArrayList(originalUrl, newUrl); - while (!originalUrl.equals(newUrl)) { - originalUrl = newUrl; - final Pair 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 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(); - } - } - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java deleted file mode 100644 index a7948bcf64..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java +++ /dev/null @@ -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); - } - } - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java deleted file mode 100644 index c207aadd28..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ /dev/null @@ -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()); - } -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/IdleConnectionMonitorThread.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/IdleConnectionMonitorThread.java deleted file mode 100644 index 4bf97e4fa6..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/IdleConnectionMonitorThread.java +++ /dev/null @@ -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(); - } - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java deleted file mode 100644 index b09a06050b..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java +++ /dev/null @@ -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); - } - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java deleted file mode 100644 index cd4979541e..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ /dev/null @@ -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); - } - } - -} diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java deleted file mode 100644 index a47a5cc743..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java +++ /dev/null @@ -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)); - } - } -} \ No newline at end of file diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java deleted file mode 100644 index f04ebff3f8..0000000000 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java +++ /dev/null @@ -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); - } -} diff --git a/apache-httpclient4/src/test/resources/.gitignore b/apache-httpclient4/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/apache-httpclient4/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.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/apache-httpclient4/src/test/resources/test.in b/apache-httpclient4/src/test/resources/test.in deleted file mode 100644 index 95d09f2b10..0000000000 --- a/apache-httpclient4/src/test/resources/test.in +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file diff --git a/apache/apache-httpclient/README.md b/apache/apache-httpclient/README.md index 08ec2a8a9c..bcc77368ed 100644 --- a/apache/apache-httpclient/README.md +++ b/apache/apache-httpclient/README.md @@ -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) - [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) -- 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 + diff --git a/apache-httpclient-2/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java b/apache/apache-httpclient/src/main/java/com/ossez/tlsversion/ClientTlsVersionExamples.java similarity index 98% rename from apache-httpclient-2/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java rename to apache/apache-httpclient/src/main/java/com/ossez/tlsversion/ClientTlsVersionExamples.java index 818d0c3cd9..467953eecf 100644 --- a/apache-httpclient-2/src/main/java/com/baeldung/tlsversion/ClientTlsVersionExamples.java +++ b/apache/apache-httpclient/src/main/java/com/ossez/tlsversion/ClientTlsVersionExamples.java @@ -1,4 +1,4 @@ -package com.baeldung.tlsversion; +package com.ossez.tlsversion; import java.io.IOException; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/GetRequestMockServer.java similarity index 98% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/GetRequestMockServer.java index 1a4f4aebf3..40283afefa 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/GetRequestMockServer.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/GetRequestMockServer.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient; +package com.ossez.httpclient; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.matchers.Times.exactly; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpAsyncClientLiveTest.java similarity index 98% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpAsyncClientLiveTest.java index 7b818f871a..cbbead5bb9 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpAsyncClientLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient; +package com.ossez.httpclient; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -97,7 +97,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer { @Test 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); final CloseableHttpAsyncClient client = HttpAsyncClients.custom() .setRoutePlanner(routePlanner) diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientCancelRequestLiveTest.java similarity index 98% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientCancelRequestLiveTest.java index d3e80c4429..5709a795c7 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientCancelRequestLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient; +package com.ossez.httpclient; import static org.assertj.core.api.Assertions.assertThat; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientMultipartLiveTest.java similarity index 99% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientMultipartLiveTest.java index 627ac2bd31..cf5d52d575 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientMultipartLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient; +package com.ossez.httpclient; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientRedirectLiveTest.java similarity index 98% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientRedirectLiveTest.java index 560eb0c8ef..426f70dead 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/HttpClientRedirectLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient; +package com.ossez.httpclient; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/ResponseUtil.java similarity index 94% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/ResponseUtil.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/ResponseUtil.java index 537f501d93..30e192e134 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/ResponseUtil.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/ResponseUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient; +package com.ossez.httpclient; import java.io.IOException; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java similarity index 99% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index 2a8665b624..26b3ff9a6c 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -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.containing; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/HttpClientConnectionManagementLiveTest.java similarity index 99% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/HttpClientConnectionManagementLiveTest.java index b0c60c0ab1..7521193937 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -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.assertNotNull; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/MultiHttpClientConnThread.java similarity index 98% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/MultiHttpClientConnThread.java index 9e4b770828..b22d638538 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/MultiHttpClientConnThread.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.conn; +package com.ossez.httpclient.conn; import java.io.IOException; diff --git a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java similarity index 97% rename from apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 6703d6880c..2850e0e8ef 100644 --- a/apache/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.conn; +package com.ossez.httpclient.conn; import java.io.IOException; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java similarity index 98% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java index 6a8308483b..7cb9d05966 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.cookies; +package com.ossez.httpclient.cookies; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java similarity index 99% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java index c1bb5bdddb..04ad13170b 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.expandUrl; +package com.ossez.httpclient.expandUrl; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/ApacheHttpClientUnitTest.java similarity index 98% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/ApacheHttpClientUnitTest.java index adf9a1a1a6..fd0127a4c4 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/ApacheHttpClientUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.httpclient; +package com.ossez.httpclient.httpclient; import static org.assertj.core.api.Assertions.assertThat; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ClientUtil.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/ClientUtil.java similarity index 88% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ClientUtil.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/ClientUtil.java index 2f430dbd64..8051e91846 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ClientUtil.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/ClientUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.httpclient; +package com.ossez.httpclient.httpclient; import java.io.IOException; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/GetRequestMockServer.java similarity index 98% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/GetRequestMockServer.java index 2c08cfa6e4..887fdd8455 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/GetRequestMockServer.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.httpclient; +package com.ossez.httpclient.httpclient; import org.apache.hc.core5.http.HttpStatus; import org.junit.jupiter.api.AfterAll; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/HttpClientCookBookLiveTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/HttpClientCookBookLiveTest.java similarity index 99% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/HttpClientCookBookLiveTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/HttpClientCookBookLiveTest.java index 6484b2f7e5..419349975c 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/HttpClientCookBookLiveTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/httpclient/HttpClientCookBookLiveTest.java @@ -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.hamcrest.Matchers.notNullValue; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java similarity index 94% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java index 8bf1278c3e..adfcbfdfff 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java @@ -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.impl.classic.BasicHttpClientResponseHandler; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/HttpClientUnitTest.java similarity index 94% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/HttpClientUnitTest.java index dcd3e38371..a970d554d8 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/HttpClientUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.readresponsebodystring; +package com.ossez.httpclient.readresponsebodystring; import java.io.IOException; diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java similarity index 94% rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java rename to apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java index e19fbd6c53..769754c608 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java +++ b/apache/apache-httpclient/src/test/java/com/ossez/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.httpclient.readresponsebodystring; +package com.ossez.httpclient.readresponsebodystring; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/apache-httpclient-2/src/test/resources/logback.xml b/apache/apache-httpclient/src/test/resources/logback.xml similarity index 100% rename from apache-httpclient-2/src/test/resources/logback.xml rename to apache/apache-httpclient/src/test/resources/logback.xml