JAVA-17488 (#14694)
Moved remaining apache-httpclient v4 code from apache-httpclient to apache-httpclient4
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate;
|
||||
* This test requires a localhost server over HTTPS <br>
|
||||
* It should only be manually run, not part of the automated build
|
||||
* */
|
||||
public class RestClientV4LiveManualTest {
|
||||
class RestClientV4LiveManualTest {
|
||||
|
||||
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
|
||||
|
||||
@@ -81,7 +81,7 @@ public class RestClientV4LiveManualTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
|
||||
void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
String urlOverHttps = "https://localhost:8082/httpclient-simple";
|
||||
HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||
|
||||
@@ -2,8 +2,6 @@ package com.baeldung.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
|
||||
public final class ClientUtil {
|
||||
|
||||
+1
@@ -1,4 +1,5 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
|
||||
+7
-7
@@ -9,11 +9,11 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HttpClientCancelRequestV4LiveTest {
|
||||
class HttpClientCancelRequestV4LiveTest {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
|
||||
@@ -21,18 +21,18 @@ public class HttpClientCancelRequestV4LiveTest {
|
||||
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public final void before() {
|
||||
instance = HttpClientBuilder.create().build();
|
||||
}
|
||||
|
||||
@After
|
||||
@AfterEach
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
instance = HttpClients.custom().build();
|
||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
response = instance.execute(request);
|
||||
|
||||
+20
@@ -1,5 +1,9 @@
|
||||
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;
|
||||
@@ -181,4 +185,20 @@ class HttpClientCookBookV4LiveTest {
|
||||
}
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
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 static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
|
||||
+20
@@ -92,6 +92,26 @@ class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
|
||||
|
||||
}
|
||||
|
||||
@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();
|
||||
|
||||
+30
-18
@@ -1,7 +1,7 @@
|
||||
package com.baeldung.httpclient.advancedconfig;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
import com.github.tomakehurst.wiremock.junit.WireMockRule;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
@@ -19,8 +19,10 @@ 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.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@@ -32,18 +34,29 @@ 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.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
|
||||
@Rule
|
||||
public WireMockRule serviceMock = new WireMockRule(8089);
|
||||
public WireMockServer serviceMock;
|
||||
public WireMockServer proxyMock;
|
||||
|
||||
@Rule
|
||||
public WireMockRule proxyMock = new WireMockRule(8090);
|
||||
@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
|
||||
public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
|
||||
void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
|
||||
//given
|
||||
String userAgent = "BaeldungAgent/1.0";
|
||||
serviceMock.stubFor(get(urlEqualTo("/detail"))
|
||||
@@ -59,11 +72,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
HttpResponse response = httpClient.execute(httpGet);
|
||||
|
||||
//then
|
||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
||||
void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
||||
//given
|
||||
String xmlBody = "<xml><id>1</id></xml>";
|
||||
serviceMock.stubFor(post(urlEqualTo("/person"))
|
||||
@@ -82,12 +95,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
HttpResponse response = httpClient.execute(httpPost);
|
||||
|
||||
//then
|
||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
||||
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
||||
void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
||||
//given
|
||||
proxyMock.stubFor(get(urlMatching(".*"))
|
||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||
@@ -107,13 +119,13 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
HttpResponse response = httpclient.execute(httpGet);
|
||||
|
||||
//then
|
||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
|
||||
void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
|
||||
//given
|
||||
proxyMock.stubFor(get(urlMatching("/private"))
|
||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||
@@ -152,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
HttpResponse response = httpclient.execute(httpGet, context);
|
||||
|
||||
//then
|
||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
||||
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
}
|
||||
|
||||
+9
-8
@@ -12,34 +12,35 @@ 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.Before;
|
||||
import org.junit.Test;
|
||||
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;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class HttpClientExpandUrlLiveTest {
|
||||
|
||||
class HttpClientExpandUrlLiveTest {
|
||||
|
||||
private CloseableHttpClient client;
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
@BeforeEach
|
||||
public final void beforeEach() {
|
||||
client = HttpClientBuilder.create().disableRedirectHandling().build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||
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
|
||||
public final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||
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));
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
||||
|
||||
|
||||
@Test
|
||||
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
||||
|
||||
+41
-38
@@ -1,7 +1,9 @@
|
||||
package com.baeldung.httpclient.httpclient.conn;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
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;
|
||||
@@ -24,6 +26,7 @@ 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;
|
||||
@@ -33,14 +36,14 @@ 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.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HttpClientConnectionManagementLiveTest {
|
||||
class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
|
||||
@Test
|
||||
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException {
|
||||
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);
|
||||
@@ -50,20 +53,20 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
||||
@Test
|
||||
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException {
|
||||
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"));
|
||||
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getLeased() == 1);
|
||||
assertEquals(1, poolingConnManager.getTotalStats()
|
||||
.getLeased());
|
||||
}
|
||||
|
||||
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
||||
@Test
|
||||
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
|
||||
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();
|
||||
@@ -81,13 +84,13 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
assertTrue(connManager.getTotalStats()
|
||||
.getLeased() == 0);
|
||||
assertEquals(0, connManager.getTotalStats()
|
||||
.getLeased());
|
||||
}
|
||||
|
||||
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
||||
@Test
|
||||
public final void whenIncreasingConnectionPool_thenNoEceptions() {
|
||||
final void whenIncreasingConnectionPool_thenNoEceptions() {
|
||||
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
|
||||
connManager.setMaxTotal(5);
|
||||
connManager.setDefaultMaxPerRoute(4);
|
||||
@@ -98,7 +101,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 4.2. Using Threads to Execute Connections
|
||||
@Test
|
||||
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
|
||||
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
|
||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
@@ -117,7 +120,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 5.1. A Custom Keep Alive Strategy
|
||||
@Test
|
||||
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
||||
final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
||||
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
||||
@Override
|
||||
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
|
||||
@@ -148,7 +151,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
||||
@Test
|
||||
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
|
||||
final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
|
||||
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
@@ -175,7 +178,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
||||
@Test
|
||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
|
||||
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
|
||||
HttpGet get = new HttpGet("http://echo.200please.com");
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
connManager.setDefaultMaxPerRoute(5);
|
||||
@@ -197,20 +200,20 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
||||
@Test
|
||||
public final void whenConfiguringTimeOut_thenNoExceptions() {
|
||||
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());
|
||||
assertTrue(connManager.getSocketConfig(route.getTargetHost())
|
||||
.getSoTimeout() == 5000);
|
||||
assertEquals(5000, connManager.getSocketConfig(route.getTargetHost())
|
||||
.getSoTimeout());
|
||||
}
|
||||
}
|
||||
|
||||
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
||||
@Test
|
||||
public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
|
||||
final void whenHttpClientChecksStaleConns_thenNoExceptions() {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
HttpClients.custom()
|
||||
.setDefaultRequestConfig(RequestConfig.custom()
|
||||
@@ -222,7 +225,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 8.2. Using a Stale Connection Monitor Thread
|
||||
@Test
|
||||
public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
|
||||
final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
@@ -233,8 +236,8 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
}
|
||||
|
||||
// Example 9.1. Closing Connection and Releasing Resources
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException {
|
||||
@Test
|
||||
final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
@@ -248,14 +251,14 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
connManager.close();
|
||||
connManager.shutdown();
|
||||
|
||||
client.execute(get);
|
||||
|
||||
assertTrue(response.getEntity() == null);
|
||||
assertThrows(IllegalStateException.class, () -> {
|
||||
client.execute(get);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
// Example 3.2. TESTER VERSION
|
||||
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
||||
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||
|
||||
@@ -273,13 +276,13 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join(1000);
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getLeased() == 2);
|
||||
assertEquals(2, poolingConnManager.getTotalStats()
|
||||
.getLeased());
|
||||
}
|
||||
|
||||
@Test
|
||||
// Example 4.2 Tester Version
|
||||
public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
|
||||
final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
@@ -297,7 +300,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
@Test
|
||||
// 6.2 TESTER VERSION
|
||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
||||
final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
poolingConnManager.setDefaultMaxPerRoute(5);
|
||||
poolingConnManager.setMaxTotal(5);
|
||||
@@ -316,15 +319,15 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
thread.join(10000);
|
||||
countConnMade++;
|
||||
if (countConnMade == 0) {
|
||||
assertTrue(thread.getLeasedConn() == 5);
|
||||
assertEquals(5, thread.getLeasedConn());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("Very Long Running")
|
||||
@Disabled("Very Long Running")
|
||||
// 8.2 TESTER VERSION
|
||||
public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
|
||||
final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
@@ -340,10 +343,10 @@ public class HttpClientConnectionManagementLiveTest {
|
||||
thread2.start();
|
||||
thread2.join();
|
||||
thread3.start();
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getAvailable() == 1);
|
||||
assertEquals(1, poolingConnManager.getTotalStats()
|
||||
.getAvailable());
|
||||
thread3.join(32000);
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getAvailable() == 0);
|
||||
assertEquals(0, poolingConnManager.getTotalStats()
|
||||
.getAvailable());
|
||||
}
|
||||
}
|
||||
|
||||
-1
@@ -3,7 +3,6 @@ package com.baeldung.httpclient.httpclient.conn;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
|
||||
-1
@@ -2,7 +2,6 @@ package com.baeldung.httpclient.httpclient.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
|
||||
+4
-3
@@ -6,18 +6,19 @@ 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.Test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class ApacheHttpClientUnitTest {
|
||||
class ApacheHttpClientUnitTest {
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||
|
||||
@Test
|
||||
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
||||
void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
||||
HttpGet request = new HttpGet(DUMMY_URL);
|
||||
|
||||
try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) {
|
||||
|
||||
+9
-9
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ApacheHttpClientRetryLiveTest {
|
||||
class ApacheHttpClientRetryLiveTest {
|
||||
|
||||
private Integer requestCounter;
|
||||
private CloseableHttpClient httpClient;
|
||||
@@ -93,14 +93,14 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
|
||||
void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
|
||||
createFailingHttpClient();
|
||||
assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200")));
|
||||
assertThat(requestCounter).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
|
||||
void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
|
||||
createDefaultApacheHttpClient();
|
||||
HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1"));
|
||||
|
||||
@@ -109,7 +109,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
|
||||
void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
|
||||
createDefaultApacheHttpClient();
|
||||
HttpGet request = new HttpGet(URI.create("https://httpstat.us/500"));
|
||||
|
||||
@@ -120,7 +120,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
|
||||
void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
|
||||
createFailingHttpClient();
|
||||
HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500"));
|
||||
|
||||
@@ -129,7 +129,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
|
||||
void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
|
||||
createFailingHttpClient();
|
||||
HttpPut request = new HttpPut(URI.create("https://httpstat.us/500"));
|
||||
|
||||
@@ -138,7 +138,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
|
||||
void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
|
||||
createHttpClientWithRetryHandler();
|
||||
|
||||
HttpPost request = new HttpPost(URI.create("https://httpstat.us/200"));
|
||||
@@ -148,7 +148,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
|
||||
void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
|
||||
createHttpClientWithCustomRetryHandler();
|
||||
|
||||
HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200"));
|
||||
@@ -158,7 +158,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
|
||||
void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
|
||||
createHttpClientWithRetriesDisabled();
|
||||
HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user