JAVA-17488 (#14694)

Moved remaining apache-httpclient v4 code from apache-httpclient to apache-httpclient4
This commit is contained in:
panos-kakos
2023-09-13 13:16:19 +03:00
committed by GitHub
parent d167545325
commit ac590b3823
30 changed files with 220 additions and 372 deletions
@@ -4,10 +4,10 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.hc.core5.http.ParseException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
@@ -19,6 +19,7 @@ import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import java.io.BufferedReader;
import java.io.File;
@@ -30,9 +31,6 @@ import java.net.URL;
class HttpClientMultipartLiveTest extends GetRequestMockServer {
// No longer available
// private static final String SERVER = "http://echo.200please.com";
private static final String SERVER = "http://localhost:8080/spring-mvc-java/stub/multipart";
private static final String TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg";
@@ -1,15 +1,16 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.DefaultRedirectStrategy;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
@@ -8,7 +8,7 @@ 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;
import java.io.IOException;
@@ -29,21 +29,34 @@ import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class HttpClientAdvancedConfigurationIntegrationTest {
import com.github.tomakehurst.wiremock.WireMockServer;
@Rule
public WireMockRule serviceMock = new WireMockRule(8089);
class HttpClientAdvancedConfigurationIntegrationTest {
@Rule
public WireMockRule proxyMock = new WireMockRule(8090);
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
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.getCode(), 200);
assertEquals(200, response.getCode());
}
@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,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
}
@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,7 +120,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@@ -151,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@@ -1,59 +0,0 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
public class HttpClientBasicPostLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests - non-GET
@Test
public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
instance.execute(new HttpPost(SAMPLE_URL));
}
@Test
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
final HttpPost request = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity("in the body of the POST"));
instance.execute(request);
}
@Test
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
final HttpPost request = new HttpPost(SAMPLE_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));
instance.execute(request);
}
}
@@ -1,75 +0,0 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
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.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class HttpClientLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests
@Test(expected = ConnectTimeoutException.class)
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setConfig(requestConfig);
response = instance.execute(request);
}
// tests - configs
@Test
public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException {
instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build();
response = instance.execute(new HttpGet(SAMPLE_URL));
}
@Test
public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = instance.execute(request);
}
@Test
public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
response = instance.execute(new HttpGet(SAMPLE_URL));
final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
}
}
@@ -1,37 +0,0 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.GetRequestMockServer;
import com.baeldung.httpclient.ResponseUtil;
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 java.io.IOException;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
*/
public class HttpClientSandboxLiveTest extends GetRequestMockServer {
@Test
public 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);
}
}
@@ -1,5 +1,6 @@
package com.baeldung.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.assertTrue;
@@ -34,14 +35,13 @@ import org.apache.hc.core5.pool.PoolStats;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.junit.Assert;
import org.junit.Test;
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 ExecutionException, InterruptedException, TimeoutException {
final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException {
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
@@ -51,7 +51,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
@Test
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
@@ -65,7 +65,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
@Test
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException {
final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
@@ -83,8 +83,7 @@ public class HttpClientConnectionManagementLiveTest {
thread1.join();
thread2.join();
Assert.assertTrue(connManager.getTotalStats()
.getLeased() == 0);
assertEquals(0, connManager.getTotalStats().getLeased());
client1.close();
client2.close();
connManager.close();
@@ -92,7 +91,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
@Test
public final void whenIncreasingConnectionPool_thenNoExceptions() {
final void whenIncreasingConnectionPool_thenNoExceptions() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
@@ -103,7 +102,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 4.2. Using Threads to Execute Connections
@Test
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
@@ -133,7 +132,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 TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
@@ -162,7 +161,7 @@ public class HttpClientConnectionManagementLiveTest {
//Example 6.1. BasicHttpClientConnectionManager Connection Reuse
@Test
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException {
final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException {
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
final HttpContext context = new BasicHttpContext();
@@ -184,7 +183,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
@Test
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(6);
@@ -208,7 +207,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 7.1. Setting Socket Timeout to 5 Seconds
@Test
public final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException {
final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException {
final HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
final HttpContext context = new BasicHttpContext();
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
@@ -227,7 +226,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 8.1. Setting the HttpClient to Check for Stale Connections
@Test
public final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
try (final CloseableHttpClient httpclient = HttpClients.custom()
@@ -266,7 +265,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 9.1. Closing Connection and Releasing Resources
@Test
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws IOException {
final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
@@ -282,7 +281,7 @@ public class HttpClientConnectionManagementLiveTest {
@Test
// Example 3.2. TESTER VERSION
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
@@ -300,8 +299,7 @@ public class HttpClientConnectionManagementLiveTest {
thread2.start();
thread1.join();
thread2.join(1000);
Assert.assertTrue(poolingConnManager.getTotalStats()
.getLeased() == 2);
assertEquals(2, poolingConnManager.getTotalStats().getLeased());
client1.close();
client2.close();
@@ -1,41 +0,0 @@
package com.baeldung.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();
}
}
}
@@ -6,7 +6,6 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;