提交 Apache HTTP httpClient 的处理到 Apache 模块下面。
虽然近期有关 Http 的处理更多有使用 okhttp 替代的趋势但 httpclient 还是需要知道和了解的。
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1 @@
|
||||
some content
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
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.hc.core5.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 final String SERVER_ADDRESS = "127.0.0.1";
|
||||
|
||||
public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1";
|
||||
|
||||
public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
System.out.println("Free port " + serverPort);
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
|
||||
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
|
||||
|
||||
client.when(
|
||||
request()
|
||||
.withPath(SECURITY_PATH)
|
||||
.withMethod("GET"),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
|
||||
client.when(
|
||||
request()
|
||||
.withPath(UPLOAD_PATH)
|
||||
.withMethod("POST"),
|
||||
exactly(4)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
.withHeader("Content-Type", "multipart/form-data")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort() throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
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.hc.client5.http.async.methods.SimpleHttpRequest;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
|
||||
import org.apache.hc.client5.http.auth.AuthScope;
|
||||
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.cookie.BasicCookieStore;
|
||||
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
|
||||
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
|
||||
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
|
||||
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
|
||||
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
|
||||
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
|
||||
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
|
||||
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
import org.apache.hc.core5.ssl.SSLContexts;
|
||||
import org.apache.hc.core5.ssl.TrustStrategy;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
||||
class HttpAsyncClientLiveTest extends GetRequestMockServer {
|
||||
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 SimpleHttpRequest request = SimpleRequestBuilder.get(HOST_WITH_COOKIE)
|
||||
.build();
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
|
||||
.build();
|
||||
client.start();
|
||||
|
||||
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
|
||||
assertThat(response.getCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final IOReactorConfig ioReactorConfig = IOReactorConfig
|
||||
.custom()
|
||||
.build();
|
||||
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
|
||||
.setIOReactorConfig(ioReactorConfig)
|
||||
.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 HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
|
||||
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
|
||||
.setRoutePlanner(routePlanner)
|
||||
.build();
|
||||
client.start();
|
||||
|
||||
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY);
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getCode(), 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 TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
|
||||
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
|
||||
.setSslContext(sslContext)
|
||||
.build();
|
||||
|
||||
final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
|
||||
.setTlsStrategy(tlsStrategy)
|
||||
.build();
|
||||
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
|
||||
.setConnectionManager(cm)
|
||||
.build();
|
||||
|
||||
client.start();
|
||||
|
||||
final SimpleHttpRequest request = new SimpleHttpRequest("GET", HOST_WITH_SSL);
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, null);
|
||||
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getCode(), 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 SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_COOKIE);
|
||||
|
||||
final HttpContext localContext = new BasicHttpContext();
|
||||
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
|
||||
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, localContext, null);
|
||||
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
final UsernamePasswordCredentials credentials =
|
||||
new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray());
|
||||
credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials);
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients
|
||||
.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider).build();
|
||||
|
||||
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
|
||||
client.start();
|
||||
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, null);
|
||||
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getCode(), 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<SimpleHttpResponse> future = client.execute(SimpleRequestBuilder.copy(request).build(), context, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getCode(), equalTo(200));
|
||||
} catch (final Exception ex) {
|
||||
System.out.println(ex.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HttpClientCancelRequestLiveTest {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
|
||||
@Test
|
||||
void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
httpClient.execute(request, response -> {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getCode());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
if (entity != null) {
|
||||
// Closes this stream and releases any system resources
|
||||
entity.close();
|
||||
}
|
||||
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
|
||||
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
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;
|
||||
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.hc.client5.http.entity.mime.StringBody;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
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;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
|
||||
class HttpClientMultipartLiveTest extends GetRequestMockServer {
|
||||
|
||||
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";
|
||||
private static final String ZIPFILENAME = "zipFile.zip";
|
||||
private HttpPost post;
|
||||
private BufferedReader rd;
|
||||
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
post = new HttpPost(SERVER);
|
||||
String URL = "http://localhost:" + serverPort + "/spring-mvc-java/stub/multipart";
|
||||
post = new HttpPost(URL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
|
||||
final File file = new File(url.getPath());
|
||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||
final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
|
||||
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
|
||||
//
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setMode(HttpMultipartMode.LEGACY);
|
||||
builder.addPart("file", fileBody);
|
||||
builder.addPart("text1", stringBody1);
|
||||
builder.addPart("text2", stringBody2);
|
||||
final HttpEntity entity = builder.build();
|
||||
|
||||
post.setEntity(entity);
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
client.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
final File file = new File(url.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setMode(HttpMultipartMode.LEGACY);
|
||||
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME);
|
||||
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
client.execute(post, response -> {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||
final File file = new File(url2.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setMode(HttpMultipartMode.LEGACY);
|
||||
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME);
|
||||
builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME);
|
||||
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
client.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
inputStream.close();
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException {
|
||||
final String message = "This is a multipart post";
|
||||
final byte[] bytes = "binary code".getBytes();
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setMode(HttpMultipartMode.LEGACY);
|
||||
builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME);
|
||||
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
httpClient.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
private String getContent(HttpEntity httpEntity) throws IOException {
|
||||
rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
|
||||
String body = "";
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((body = rd.readLine()) != null) {
|
||||
content.append(body)
|
||||
.append("\n");
|
||||
}
|
||||
return content.toString()
|
||||
.trim();
|
||||
}
|
||||
|
||||
private String getContentTypeHeader() {
|
||||
return post.getEntity()
|
||||
.getContentType();
|
||||
}
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
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 java.io.IOException;
|
||||
|
||||
class HttpClientRedirectLiveTest {
|
||||
|
||||
@Test
|
||||
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
|
||||
final HttpGet request = new HttpGet("http://t.co/I5YYd9tddw");
|
||||
|
||||
try (CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.disableRedirectHandling()
|
||||
.build()) {
|
||||
httpClient.execute(request, response -> {
|
||||
assertThat(response.getCode(), equalTo(301));
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||
|
||||
final HttpPost request = new HttpPost("http://t.co/I5YYd9tddw");
|
||||
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
httpClient.execute(request, response -> {
|
||||
assertThat(response.getCode(), equalTo(200));
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenRedirectingPOST_whenUsingDefaultRedirectStrategy_thenRedirected() throws IOException {
|
||||
|
||||
final HttpPost request = new HttpPost("http://t.co/I5YYd9tddw");
|
||||
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.setRedirectStrategy(new DefaultRedirectStrategy())
|
||||
.build()) {
|
||||
httpClient.execute(request, response -> {
|
||||
assertThat(response.getCode(), equalTo(200));
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
package com.baeldung.httpclient.advancedconfig;
|
||||
|
||||
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;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.auth.AuthCache;
|
||||
import org.apache.hc.client5.http.auth.AuthScope;
|
||||
import org.apache.hc.client5.http.auth.CredentialsProvider;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
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.auth.BasicAuthCache;
|
||||
import org.apache.hc.client5.http.impl.auth.BasicScheme;
|
||||
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
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.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
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.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
||||
//given
|
||||
String xmlBody = "<xml><id>1</id></xml>";
|
||||
serviceMock.stubFor(post(urlEqualTo("/person"))
|
||||
.withHeader("Content-Type", equalTo("application/xml"))
|
||||
.withRequestBody(equalTo(xmlBody))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(200)));
|
||||
|
||||
HttpClient httpClient = HttpClients.createDefault();
|
||||
HttpPost httpPost = new HttpPost("http://localhost:8089/person");
|
||||
httpPost.setHeader("Content-Type", "application/xml");
|
||||
StringEntity xmlEntity = new StringEntity(xmlBody);
|
||||
httpPost.setEntity(xmlEntity);
|
||||
|
||||
//when
|
||||
HttpResponse response = httpClient.execute(httpPost);
|
||||
|
||||
//then
|
||||
assertEquals(200, response.getCode());
|
||||
|
||||
}
|
||||
|
||||
@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.getCode());
|
||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public 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 = CredentialsProviderBuilder.create()
|
||||
.add(new AuthScope(proxy), "username_admin", "secret_password".toCharArray())
|
||||
.build();
|
||||
|
||||
// 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");
|
||||
httpGet.setHeader("Authorization", StandardAuthScheme.BASIC);
|
||||
HttpResponse response = httpclient.execute(httpGet, context);
|
||||
|
||||
//then
|
||||
assertEquals(200, response.getCode());
|
||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
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;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Iterator;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
|
||||
import org.apache.hc.client5.http.HttpRoute;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.config.ConnectionConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.io.ConnectionEndpoint;
|
||||
import org.apache.hc.client5.http.io.LeaseRequest;
|
||||
import org.apache.hc.core5.http.HeaderElement;
|
||||
import org.apache.hc.core5.http.HeaderElements;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.message.MessageSupport;
|
||||
import org.apache.hc.core5.http.message.StatusLine;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
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.jupiter.api.Test;
|
||||
|
||||
class HttpClientConnectionManagementLiveTest {
|
||||
|
||||
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
|
||||
@Test
|
||||
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);
|
||||
assertNotNull(connRequest.get(Timeout.ZERO_MILLISECONDS));
|
||||
connMgr.close();
|
||||
}
|
||||
|
||||
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
||||
@Test
|
||||
final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws 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);
|
||||
client.close();
|
||||
poolingConnManager.close();
|
||||
}
|
||||
|
||||
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
||||
@Test
|
||||
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();
|
||||
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());
|
||||
client1.close();
|
||||
client2.close();
|
||||
connManager.close();
|
||||
}
|
||||
|
||||
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
||||
@Test
|
||||
final void whenIncreasingConnectionPool_thenNoExceptions() {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
connManager.setMaxTotal(5);
|
||||
connManager.setDefaultMaxPerRoute(4);
|
||||
HttpHost host = new HttpHost("www.baeldung.com", 80);
|
||||
connManager.setMaxPerRoute(new HttpRoute(host), 5);
|
||||
connManager.close();
|
||||
}
|
||||
|
||||
// Example 4.2. Using Threads to Execute Connections
|
||||
@Test
|
||||
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
|
||||
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, connManager);
|
||||
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get, connManager);
|
||||
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get, connManager);
|
||||
MultiHttpClientConnThread thread4 = new MultiHttpClientConnThread(client, get, connManager);
|
||||
MultiHttpClientConnThread thread5 = new MultiHttpClientConnThread(client, get, connManager);
|
||||
MultiHttpClientConnThread thread6 = new MultiHttpClientConnThread(client, get, connManager);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread3.start();
|
||||
thread4.start();
|
||||
thread5.start();
|
||||
thread6.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
thread3.join();
|
||||
thread4.join();
|
||||
thread5.join();
|
||||
thread6.join();
|
||||
client.close();
|
||||
connManager.close();
|
||||
}
|
||||
|
||||
// Example 5.1. A Custom Keep Alive Strategy
|
||||
@Test
|
||||
final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
||||
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
||||
@Override
|
||||
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
|
||||
Args.notNull(response, "HTTP response");
|
||||
final Iterator<HeaderElement> it = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE);
|
||||
final HeaderElement he = it.next();
|
||||
final String param = he.getName();
|
||||
final String value = he.getValue();
|
||||
if (value != null && param.equalsIgnoreCase("timeout")) {
|
||||
try {
|
||||
return TimeValue.ofSeconds(Long.parseLong(value));
|
||||
} catch (final NumberFormatException ignore) {
|
||||
}
|
||||
}
|
||||
return TimeValue.ofSeconds(5);
|
||||
}
|
||||
|
||||
};
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
HttpClients.custom()
|
||||
.setKeepAliveStrategy(myStrategy)
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
connManager.close();
|
||||
}
|
||||
|
||||
//Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
||||
@Test
|
||||
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();
|
||||
|
||||
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
|
||||
final ConnectionEndpoint endpoint = connRequest.get(Timeout.ZERO_MILLISECONDS);
|
||||
connMgr.connect(endpoint, Timeout.ZERO_MILLISECONDS, context);
|
||||
|
||||
connMgr.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
|
||||
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(connMgr)
|
||||
.build();
|
||||
HttpGet httpGet = new HttpGet("https://www.example.com");
|
||||
client.execute(httpGet, context, response -> response);
|
||||
client.close();
|
||||
connMgr.close();
|
||||
}
|
||||
|
||||
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
||||
@Test
|
||||
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
|
||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
connManager.setDefaultMaxPerRoute(6);
|
||||
connManager.setMaxTotal(6);
|
||||
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);
|
||||
}
|
||||
client.close();
|
||||
connManager.close();
|
||||
}
|
||||
|
||||
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
||||
@Test
|
||||
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();
|
||||
|
||||
final ConnectionConfig connConfig = ConnectionConfig.custom()
|
||||
.setSocketTimeout(5, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
connManager.setDefaultConnectionConfig(connConfig);
|
||||
|
||||
final LeaseRequest leaseRequest = connManager.lease("id1", route, null);
|
||||
final ConnectionEndpoint endpoint = leaseRequest.get(Timeout.ZERO_MILLISECONDS);
|
||||
connManager.connect(endpoint, null, context);
|
||||
connManager.close();
|
||||
}
|
||||
|
||||
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
||||
@Test
|
||||
final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
|
||||
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
connManager.setMaxTotal(100);
|
||||
try (final CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.evictExpiredConnections()
|
||||
.evictIdleConnections(TimeValue.ofSeconds(2))
|
||||
.build()) {
|
||||
// create an array of URIs to perform GETs on
|
||||
final String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/"};
|
||||
|
||||
for (final String requestURI : urisToGet) {
|
||||
final HttpGet request = new HttpGet(requestURI);
|
||||
|
||||
System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri());
|
||||
|
||||
httpclient.execute(request, response -> {
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(request + "->" + new StatusLine(response));
|
||||
EntityUtils.consume(response.getEntity());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
final PoolStats stats1 = connManager.getTotalStats();
|
||||
System.out.println("Connections kept alive: " + stats1.getAvailable());
|
||||
|
||||
// Sleep 10 sec and let the connection evict or do its job
|
||||
Thread.sleep(4000);
|
||||
|
||||
final PoolStats stats2 = connManager.getTotalStats();
|
||||
System.out.println("Connections kept alive: " + stats2.getAvailable());
|
||||
|
||||
connManager.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
@Test
|
||||
// Example 3.2. TESTER VERSION
|
||||
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
|
||||
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());
|
||||
|
||||
client1.close();
|
||||
client2.close();
|
||||
poolingConnManager.close();
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.httpclient.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
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.io.entity.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());
|
||||
|
||||
|
||||
if (connManager != null) {
|
||||
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
|
||||
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
|
||||
}
|
||||
|
||||
HttpEntity entity = client.execute(get).getEntity();
|
||||
|
||||
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(entity);
|
||||
|
||||
} catch (final IOException ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.httpclient.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
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.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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1 @@
|
||||
hello world
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,49 @@
|
||||
web - 2014-01-30 20:48:07,171 [main] DEBUG o.a.h.c.protocol.RequestAuthCache - Auth cache not set in the context
|
||||
web - 2014-01-30 20:48:07,172 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection request: [route: {}->http://localhost:8080][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
|
||||
web - 2014-01-30 20:48:07,185 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {}->http://localhost:8080][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
|
||||
web - 2014-01-30 20:48:07,190 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Opening connection {}->http://localhost:8080
|
||||
web - 2014-01-30 20:48:07,192 [main] DEBUG o.a.h.c.HttpClientConnectionManager - Connecting to localhost/127.0.0.1:8080
|
||||
web - 2014-01-30 20:48:07,193 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Executing request GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
|
||||
web - 2014-01-30 20:48:07,193 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Target auth state: UNCHALLENGED
|
||||
web - 2014-01-30 20:48:07,193 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
|
||||
web - 2014-01-30 20:48:07,194 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
|
||||
web - 2014-01-30 20:48:07,194 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: localhost:8080
|
||||
web - 2014-01-30 20:48:07,194 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
|
||||
web - 2014-01-30 20:48:07,194 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.3.1 (java 1.5)
|
||||
web - 2014-01-30 20:48:07,194 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 401 Unauthorized
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Server: Apache-Coyote/1.1
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << WWW-Authenticate: Basic realm="Spring Security Application"
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: text/html;charset=utf-8
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Language: en
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Length: 1061
|
||||
web - 2014-01-30 20:48:07,203 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Thu, 30 Jan 2014 18:48:07 GMT
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.http.impl.auth.HttpAuthenticator - Authentication required
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.http.impl.auth.HttpAuthenticator - localhost:8080 requested authentication
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.h.i.c.TargetAuthenticationStrategy - Authentication schemes in the order of preference: [negotiate, Kerberos, NTLM, Digest, Basic]
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.h.i.c.TargetAuthenticationStrategy - Challenge for negotiate authentication scheme not available
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.h.i.c.TargetAuthenticationStrategy - Challenge for Kerberos authentication scheme not available
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.h.i.c.TargetAuthenticationStrategy - Challenge for NTLM authentication scheme not available
|
||||
web - 2014-01-30 20:48:07,206 [main] DEBUG o.a.h.i.c.TargetAuthenticationStrategy - Challenge for Digest authentication scheme not available
|
||||
web - 2014-01-30 20:48:07,213 [main] DEBUG o.a.http.impl.auth.HttpAuthenticator - Selected authentication options: [BASIC]
|
||||
web - 2014-01-30 20:48:07,214 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Executing request GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
|
||||
web - 2014-01-30 20:48:07,214 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Target auth state: CHALLENGED
|
||||
web - 2014-01-30 20:48:07,214 [main] DEBUG o.a.http.impl.auth.HttpAuthenticator - Generating response to an authentication challenge using basic scheme
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: localhost:8080
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.3.1 (java 1.5)
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
|
||||
web - 2014-01-30 20:48:07,215 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Authorization: Basic dXNlcjE6dXNlcjFQYXNz
|
||||
web - 2014-01-30 20:48:07,217 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK
|
||||
web - 2014-01-30 20:48:07,217 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Server: Apache-Coyote/1.1
|
||||
web - 2014-01-30 20:48:07,217 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: application/json;charset=UTF-8
|
||||
web - 2014-01-30 20:48:07,217 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Transfer-Encoding: chunked
|
||||
web - 2014-01-30 20:48:07,217 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Thu, 30 Jan 2014 18:48:07 GMT
|
||||
web - 2014-01-30 20:48:07,218 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
|
||||
web - 2014-01-30 20:48:07,218 [main] DEBUG o.a.http.impl.auth.HttpAuthenticator - Authentication succeeded
|
||||
web - 2014-01-30 20:48:07,219 [main] DEBUG o.a.h.i.c.TargetAuthenticationStrategy - Caching 'basic' auth scheme for http://localhost:8080
|
||||
web - 2014-01-30 20:48:07,227 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection [id: 0][route: {}->http://localhost:8080] can be kept alive indefinitely
|
||||
web - 2014-01-30 20:48:07,227 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://localhost:8080][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20]
|
||||
@@ -0,0 +1 @@
|
||||
Hello theren
|
||||
Binary file not shown.
Reference in New Issue
Block a user