JAVA-10903: Rename HttpClient Modules to Apache HttpClient (#12070)
* JAVA-10903: rename httpclient to apache-httpclient * JAVA-10903: rename httpclient-2 to apache-httpclient * JAVA-10903: update main pom
This commit is contained in:
13
apache-httpclient/.gitignore
vendored
Normal file
13
apache-httpclient/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
20
apache-httpclient/README.md
Normal file
20
apache-httpclient/README.md
Normal file
@@ -0,0 +1,20 @@
|
||||
## HttpClient 4.x
|
||||
|
||||
This module contains articles about HttpClient 4.x
|
||||
|
||||
### The Course
|
||||
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Apache HttpClient – Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
|
||||
- [Apache HttpClient 4 Cookbook](https://www.baeldung.com/httpclient4)
|
||||
- [Apache HttpClient – Follow Redirects for POST](https://www.baeldung.com/httpclient-redirect-on-http-post)
|
||||
- [Multipart Upload with Apache HttpClient](https://www.baeldung.com/httpclient-multipart-upload)
|
||||
- [Apache HttpAsyncClient Tutorial](https://www.baeldung.com/httpasyncclient-tutorial)
|
||||
- [Apache HttpClient Tutorial](https://www.baeldung.com/httpclient-guide)
|
||||
- [Advanced HttpClient Configuration](https://www.baeldung.com/httpclient-advanced-config)
|
||||
- [Apache HttpClient – Do Not Follow Redirects](https://www.baeldung.com/httpclient-stop-follow-redirect)
|
||||
- [Custom User-Agent in Apache HttpClient](https://www.baeldung.com/httpclient-user-agent-header)
|
||||
- [Apache HttpClient Connection Management](https://www.baeldung.com/httpclient-connection-management)
|
||||
- More articles: [[next -->]](../apache-httpclient-2)
|
||||
83
apache-httpclient/pom.xml
Normal file
83
apache-httpclient/pom.xml
Normal file
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-httpclient</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>apache-httpclient</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- http client -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>fluent-hc</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpasyncclient</artifactId>
|
||||
<version>${httpasyncclient.version}</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>${wiremock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>apache-httpclient</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<httpasyncclient.version>4.1.4</httpasyncclient.version>
|
||||
<!-- testing -->
|
||||
<wiremock.version>2.5.1</wiremock.version>
|
||||
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
19
apache-httpclient/src/main/resources/logback.xml
Normal file
19
apache-httpclient/src/main/resources/logback.xml
Normal file
@@ -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>
|
||||
1
apache-httpclient/src/main/resources/temp.txt
Normal file
1
apache-httpclient/src/main/resources/temp.txt
Normal file
@@ -0,0 +1 @@
|
||||
some content
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.cookie.BasicClientCookie;
|
||||
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
|
||||
import org.apache.http.impl.nio.client.HttpAsyncClients;
|
||||
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
|
||||
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
|
||||
import org.apache.http.nio.reactor.ConnectingIOReactor;
|
||||
import org.apache.http.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpAsyncClientLiveTest {
|
||||
|
||||
private static final String HOST = "http://www.google.com";
|
||||
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
|
||||
private static final String HOST_WITH_PROXY = "http://httpbin.org/";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";// "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1";
|
||||
private static final String DEFAULT_USER = "test";// "user1";
|
||||
private static final String DEFAULT_PASS = "test";// "user1Pass";
|
||||
|
||||
private static final String HOST_WITH_COOKIE = "http://yuilibrary.com/yui/docs/cookie/cookie-simple-example.html"; // "http://github.com";
|
||||
private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com";
|
||||
private static final String COOKIE_NAME = "example"; // "JSESSIONID";
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
||||
client.start();
|
||||
final HttpGet request = new HttpGet(HOST);
|
||||
|
||||
final Future<HttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
|
||||
final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build();
|
||||
client.start();
|
||||
final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" };
|
||||
|
||||
final GetThread[] threads = new GetThread[toGet.length];
|
||||
for (int i = 0; i < threads.length; i++) {
|
||||
final HttpGet request = new HttpGet(toGet[i]);
|
||||
threads[i] = new GetThread(client, request);
|
||||
}
|
||||
|
||||
for (final GetThread thread : threads) {
|
||||
thread.start();
|
||||
}
|
||||
|
||||
for (final GetThread thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
||||
client.start();
|
||||
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
|
||||
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
|
||||
final HttpGet request = new HttpGet(HOST_WITH_PROXY);
|
||||
request.setConfig(config);
|
||||
final Future<HttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
||||
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
|
||||
|
||||
client.start();
|
||||
final HttpGet request = new HttpGet(HOST_WITH_SSL);
|
||||
final Future<HttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final BasicCookieStore cookieStore = new BasicCookieStore();
|
||||
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
|
||||
cookie.setDomain(COOKIE_DOMAIN);
|
||||
cookie.setPath("/");
|
||||
cookieStore.addCookie(cookie);
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
|
||||
client.start();
|
||||
final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
|
||||
|
||||
final HttpContext localContext = new BasicHttpContext();
|
||||
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
|
||||
|
||||
final Future<HttpResponse> future = client.execute(request, localContext, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
|
||||
final CredentialsProvider provider = new BasicCredentialsProvider();
|
||||
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
||||
provider.setCredentials(AuthScope.ANY, creds);
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
|
||||
|
||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
client.start();
|
||||
final Future<HttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
static class GetThread extends Thread {
|
||||
|
||||
private final CloseableHttpAsyncClient client;
|
||||
private final HttpContext context;
|
||||
private final HttpGet request;
|
||||
|
||||
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
|
||||
this.client = client;
|
||||
context = HttpClientContext.create();
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
final Future<HttpResponse> future = client.execute(request, context, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
} catch (final Exception ex) {
|
||||
System.out.println(ex.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.mime.HttpMultipartMode;
|
||||
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.http.entity.mime.content.FileBody;
|
||||
import org.apache.http.entity.mime.content.StringBody;
|
||||
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.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;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class HttpClientMultipartLiveTest {
|
||||
|
||||
// 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";
|
||||
private static final String ZIPFILENAME = "zipFile.zip";
|
||||
private static final Logger LOGGER = Logger.getLogger("com.baeldung.httpclient.HttpClientMultipartLiveTest");
|
||||
private CloseableHttpClient client;
|
||||
private HttpPost post;
|
||||
private BufferedReader rd;
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
client = HttpClientBuilder.create()
|
||||
.build();
|
||||
post = new HttpPost(SERVER);
|
||||
}
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
post.completed();
|
||||
try {
|
||||
client.close();
|
||||
} catch (final IOException e1) {
|
||||
LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
|
||||
throw e1;
|
||||
}
|
||||
try {
|
||||
rd.close();
|
||||
} catch (final IOException e) {
|
||||
LOGGER.log(Level.SEVERE, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final 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.BROWSER_COMPATIBLE);
|
||||
builder.addPart("file", fileBody);
|
||||
builder.addPart("text1", stringBody1);
|
||||
builder.addPart("text2", stringBody2);
|
||||
final HttpEntity entity = builder.build();
|
||||
//
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final 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.BROWSER_COMPATIBLE);
|
||||
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME);
|
||||
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final 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.BROWSER_COMPATIBLE);
|
||||
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);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
inputStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
final String message = "This is a multipart post";
|
||||
final byte[] bytes = "binary code".getBytes();
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
|
||||
builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME);
|
||||
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
private String getContent() throws IOException {
|
||||
rd = new BufferedReader(new InputStreamReader(response.getEntity()
|
||||
.getContent()));
|
||||
String body = "";
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((body = rd.readLine()) != null) {
|
||||
content.append(body).append("\n");
|
||||
}
|
||||
return content.toString().trim();
|
||||
}
|
||||
|
||||
private String getContentTypeHeader() throws IOException {
|
||||
return post.getEntity()
|
||||
.getContentType()
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpHead;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.DefaultRedirectStrategy;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.client.LaxRedirectStrategy;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class HttpClientRedirectLiveTest {
|
||||
|
||||
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
|
||||
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
instance = HttpClients.custom().disableRedirectHandling().build();
|
||||
|
||||
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
|
||||
response = instance.execute(httpGet);
|
||||
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
instance = HttpClientBuilder.create().disableRedirectHandling().build();
|
||||
response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||
}
|
||||
|
||||
// redirect with POST
|
||||
|
||||
@Test
|
||||
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
|
||||
instance = HttpClientBuilder.create().build();
|
||||
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
|
||||
/** Redirectable methods. */
|
||||
private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
|
||||
|
||||
@Override
|
||||
protected boolean isRedirectable(final String method) {
|
||||
return Arrays.stream(REDIRECT_METHODS)
|
||||
.anyMatch(m -> m.equalsIgnoreCase(method));
|
||||
}
|
||||
}).build();
|
||||
|
||||
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
|
||||
|
||||
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
|
||||
instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
|
||||
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public final class ResponseUtil {
|
||||
private ResponseUtil() {
|
||||
}
|
||||
|
||||
public static void closeResponse(CloseableHttpResponse response) throws IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
entity.getContent().close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.baeldung.httpclient.advancedconfig;
|
||||
|
||||
|
||||
import com.github.tomakehurst.wiremock.junit.WireMockRule;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.AuthCache;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.auth.BasicScheme;
|
||||
import org.apache.http.impl.client.BasicAuthCache;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||
|
||||
@Rule
|
||||
public WireMockRule serviceMock = new WireMockRule(8089);
|
||||
|
||||
@Rule
|
||||
public WireMockRule proxyMock = new WireMockRule(8090);
|
||||
|
||||
@Test
|
||||
public 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(response.getStatusLine().getStatusCode(), 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public 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(response.getStatusLine().getStatusCode(), 200);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public 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(response.getStatusLine().getStatusCode(), 200);
|
||||
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 = new BasicCredentialsProvider();
|
||||
credentialsProvider.setCredentials(new AuthScope(proxy),
|
||||
new UsernamePasswordCredentials("username_admin", "secret_password"));
|
||||
|
||||
|
||||
// Create AuthCache instance
|
||||
AuthCache authCache = new BasicAuthCache();
|
||||
|
||||
// Generate BASIC scheme object and add it to the local auth cache
|
||||
BasicScheme basicAuth = new BasicScheme();
|
||||
authCache.put(proxy, basicAuth);
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
context.setCredentialsProvider(credentialsProvider);
|
||||
context.setAuthCache(authCache);
|
||||
|
||||
|
||||
HttpClient httpclient = HttpClients.custom()
|
||||
.setRoutePlanner(routePlanner)
|
||||
.setDefaultCredentialsProvider(credentialsProvider)
|
||||
.build();
|
||||
|
||||
|
||||
//when
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
|
||||
HttpResponse response = httpclient.execute(httpGet, context);
|
||||
|
||||
//then
|
||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.httpclient.base;
|
||||
|
||||
import com.baeldung.httpclient.ResponseUtil;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
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.client.HttpClients;
|
||||
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(50).setConnectTimeout(50).setSocketTimeout(20).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()));
|
||||
}
|
||||
|
||||
// tests - cancel request
|
||||
|
||||
@Test
|
||||
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
instance = HttpClients.custom().build();
|
||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
response = instance.execute(request);
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.httpclient.base;
|
||||
|
||||
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.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
public class HttpClientSandboxLiveTest {
|
||||
|
||||
@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:8080/spring-security-rest-basic-auth/api/foos/1");
|
||||
final CloseableHttpResponse response = client.execute(httpGet);
|
||||
|
||||
System.out.println(response.getStatusLine());
|
||||
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package com.baeldung.httpclient.conn;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.http.HeaderElement;
|
||||
import org.apache.http.HeaderElementIterator;
|
||||
import org.apache.http.HttpClientConnection;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.config.SocketConfig;
|
||||
import org.apache.http.conn.ConnectionKeepAliveStrategy;
|
||||
import org.apache.http.conn.ConnectionPoolTimeoutException;
|
||||
import org.apache.http.conn.ConnectionRequest;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.message.BasicHeaderElementIterator;
|
||||
import org.apache.http.protocol.HTTP;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.protocol.HttpCoreContext;
|
||||
import org.apache.http.protocol.HttpRequestExecutor;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public 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 {
|
||||
try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) {
|
||||
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
||||
final ConnectionRequest connRequest = connManager.requestConnection(route, null);
|
||||
assertNotNull(connRequest.get(1000, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
||||
@Test
|
||||
public 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);
|
||||
}
|
||||
|
||||
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
||||
@Test
|
||||
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
|
||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client1 = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
CloseableHttpClient client2 = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
|
||||
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1);
|
||||
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
assertTrue(connManager.getTotalStats()
|
||||
.getLeased() == 0);
|
||||
}
|
||||
|
||||
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
||||
@Test
|
||||
public final void whenIncreasingConnectionPool_thenNoEceptions() {
|
||||
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
|
||||
connManager.setMaxTotal(5);
|
||||
connManager.setDefaultMaxPerRoute(4);
|
||||
HttpHost host = new HttpHost("www.baeldung.com", 80);
|
||||
connManager.setMaxPerRoute(new HttpRoute(host), 5);
|
||||
}
|
||||
}
|
||||
|
||||
// Example 4.2. Using Threads to Execute Connections
|
||||
@Test
|
||||
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
|
||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get);
|
||||
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get);
|
||||
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread3.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
thread3.join();
|
||||
}
|
||||
|
||||
// Example 5.1. A Custom Keep Alive Strategy
|
||||
@Test
|
||||
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
||||
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
||||
@Override
|
||||
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
|
||||
final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
|
||||
while (it.hasNext()) {
|
||||
final HeaderElement he = it.nextElement();
|
||||
final String param = he.getName();
|
||||
final String value = he.getValue();
|
||||
if ((value != null) && param.equalsIgnoreCase("timeout")) {
|
||||
return Long.parseLong(value) * 1000;
|
||||
}
|
||||
}
|
||||
final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
|
||||
if ("localhost".equalsIgnoreCase(target.getHostName())) {
|
||||
return 10 * 1000;
|
||||
} else {
|
||||
return 5 * 1000;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
HttpClients.custom()
|
||||
.setKeepAliveStrategy(myStrategy)
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
}
|
||||
|
||||
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
||||
@Test
|
||||
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
|
||||
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
// low level
|
||||
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
|
||||
ConnectionRequest connRequest = basicConnManager.requestConnection(route, null);
|
||||
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
|
||||
basicConnManager.connect(conn, route, 1000, context);
|
||||
basicConnManager.routeComplete(conn, route, context);
|
||||
|
||||
HttpRequestExecutor exeRequest = new HttpRequestExecutor();
|
||||
context.setTargetHost((new HttpHost("www.baeldung.com", 80)));
|
||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||
exeRequest.execute(get, conn, context);
|
||||
|
||||
basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
|
||||
|
||||
// high level
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(basicConnManager)
|
||||
.build();
|
||||
client.execute(get);
|
||||
}
|
||||
|
||||
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
||||
@Test
|
||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
|
||||
HttpGet get = new HttpGet("http://echo.200please.com");
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
connManager.setDefaultMaxPerRoute(5);
|
||||
connManager.setMaxTotal(5);
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
|
||||
for (int i = 0; i < threads.length; i++) {
|
||||
threads[i] = new MultiHttpClientConnThread(client, get, connManager);
|
||||
}
|
||||
for (MultiHttpClientConnThread thread : threads) {
|
||||
thread.start();
|
||||
}
|
||||
for (MultiHttpClientConnThread thread : threads) {
|
||||
thread.join(1000);
|
||||
}
|
||||
}
|
||||
|
||||
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
||||
@Test
|
||||
public 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);
|
||||
}
|
||||
}
|
||||
|
||||
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
||||
@Test
|
||||
public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
HttpClients.custom()
|
||||
.setDefaultRequestConfig(RequestConfig.custom()
|
||||
.setStaleConnectionCheckEnabled(true)
|
||||
.build())
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
}
|
||||
|
||||
// Example 8.2. Using a Stale Connection Monitor Thread
|
||||
@Test
|
||||
public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(connManager);
|
||||
staleMonitor.start();
|
||||
staleMonitor.join(1000);
|
||||
}
|
||||
|
||||
// Example 9.1. Closing Connection and Releasing Resources
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException {
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.build();
|
||||
final HttpGet get = new HttpGet("http://google.com");
|
||||
CloseableHttpResponse response = client.execute(get);
|
||||
|
||||
EntityUtils.consume(response.getEntity());
|
||||
response.close();
|
||||
client.close();
|
||||
connManager.close();
|
||||
connManager.shutdown();
|
||||
|
||||
client.execute(get);
|
||||
|
||||
assertTrue(response.getEntity() == null);
|
||||
}
|
||||
|
||||
@Test
|
||||
// Example 3.2. TESTER VERSION
|
||||
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
final CloseableHttpClient client1 = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
.build();
|
||||
final CloseableHttpClient client2 = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
.build();
|
||||
|
||||
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager);
|
||||
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join(1000);
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getLeased() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
// Example 4.2 Tester Version
|
||||
public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
.build();
|
||||
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
|
||||
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
|
||||
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread3.start();
|
||||
thread1.join(10000);
|
||||
thread2.join(10000);
|
||||
thread3.join(10000);
|
||||
}
|
||||
|
||||
@Test
|
||||
// 6.2 TESTER VERSION
|
||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
poolingConnManager.setDefaultMaxPerRoute(5);
|
||||
poolingConnManager.setMaxTotal(5);
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
.build();
|
||||
final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
|
||||
int countConnMade = 0;
|
||||
for (int i = 0; i < threads.length; i++) {
|
||||
threads[i] = new MultiHttpClientConnThread(client, new HttpGet("http://www.baeldung.com/"), poolingConnManager);
|
||||
}
|
||||
for (final MultiHttpClientConnThread thread : threads) {
|
||||
thread.start();
|
||||
}
|
||||
for (final MultiHttpClientConnThread thread : threads) {
|
||||
thread.join(10000);
|
||||
countConnMade++;
|
||||
if (countConnMade == 0) {
|
||||
assertTrue(thread.getLeasedConn() == 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("Very Long Running")
|
||||
// 8.2 TESTER VERSION
|
||||
public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
|
||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
CloseableHttpClient client = HttpClients.custom()
|
||||
.setConnectionManager(poolingConnManager)
|
||||
.build();
|
||||
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);
|
||||
final HttpGet get = new HttpGet("http://google.com");
|
||||
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
|
||||
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
|
||||
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
|
||||
staleMonitor.start();
|
||||
thread1.start();
|
||||
thread1.join();
|
||||
thread2.start();
|
||||
thread2.join();
|
||||
thread3.start();
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getAvailable() == 1);
|
||||
thread3.join(32000);
|
||||
assertTrue(poolingConnManager.getTotalStats()
|
||||
.getAvailable() == 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.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;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class MultiHttpClientConnThread extends Thread {
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private final CloseableHttpClient client;
|
||||
private final HttpGet get;
|
||||
|
||||
private PoolingHttpClientConnectionManager connManager;
|
||||
private int leasedConn;
|
||||
|
||||
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
|
||||
this.client = client;
|
||||
this.get = get;
|
||||
this.connManager = connManager;
|
||||
leasedConn = 0;
|
||||
}
|
||||
|
||||
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
|
||||
this.client = client;
|
||||
this.get = get;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
final int getLeasedConn() {
|
||||
return leasedConn;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public final void run() {
|
||||
try {
|
||||
logger.debug("Thread Running: " + getName());
|
||||
|
||||
logger.debug("Thread Running: " + getName());
|
||||
|
||||
if (connManager != null) {
|
||||
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
|
||||
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
|
||||
}
|
||||
|
||||
final HttpResponse response = client.execute(get);
|
||||
|
||||
if (connManager != null) {
|
||||
leasedConn = connManager.getTotalStats().getLeased();
|
||||
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
|
||||
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
|
||||
}
|
||||
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} catch (final IOException ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
13
apache-httpclient/src/test/resources/.gitignore
vendored
Normal file
13
apache-httpclient/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
1
apache-httpclient/src/test/resources/test.in
Normal file
1
apache-httpclient/src/test/resources/test.in
Normal file
@@ -0,0 +1 @@
|
||||
hello world
|
||||
BIN
apache-httpclient/src/test/resources/uploads/image.jpg
Normal file
BIN
apache-httpclient/src/test/resources/uploads/image.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
49
apache-httpclient/src/test/resources/uploads/sandbox.txt
Normal file
49
apache-httpclient/src/test/resources/uploads/sandbox.txt
Normal file
@@ -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]
|
||||
1
apache-httpclient/src/test/resources/uploads/temp.txt
Normal file
1
apache-httpclient/src/test/resources/uploads/temp.txt
Normal file
@@ -0,0 +1 @@
|
||||
Hello theren
|
||||
BIN
apache-httpclient/src/test/resources/uploads/zipFile.zip
Normal file
BIN
apache-httpclient/src/test/resources/uploads/zipFile.zip
Normal file
Binary file not shown.
Reference in New Issue
Block a user