Refactor HttpClient (#2272)

This commit is contained in:
Grzegorz Piwowarek 2017-07-19 11:16:44 +03:00 committed by GitHub
parent 14456eb92d
commit ffd66faa7d
21 changed files with 230 additions and 350 deletions

View File

@ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest {
@Test @Test
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build(); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build();
@ -160,7 +155,7 @@ public class HttpAsyncClientLiveTest {
private final HttpContext context; private final HttpContext context;
private final HttpGet request; private final HttpGet request;
public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
this.client = client; this.client = client;
context = HttpClientContext.create(); context = HttpClientContext.create();
this.request = request; this.request = request;

View File

@ -1,11 +1,7 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import java.io.IOException; import com.google.common.collect.Lists;
import java.io.InputStream;
import java.util.List;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
@ -20,7 +16,8 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.google.common.collect.Lists; import java.io.IOException;
import java.util.List;
public class HttpClientHeadersLiveTest { public class HttpClientHeadersLiveTest {
@ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests - headers - deprecated // tests - headers - deprecated

View File

@ -1,22 +1,7 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
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 org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
@ -30,6 +15,20 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; 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 { public class HttpClientMultipartLiveTest {
// No longer available // No longer available
@ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest {
@Before @Before
public final void before() { public final void before() {
client = HttpClientBuilder.create() client = HttpClientBuilder.create()
.build(); .build();
post = new HttpPost(SERVER); post = new HttpPost(SERVER);
} }
@ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest {
LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw e; throw e;
} }
try { ResponseUtil.closeResponse(response);
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests
@ -83,8 +74,8 @@ public class HttpClientMultipartLiveTest {
@Test @Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME); .getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath()); final File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
@ -102,7 +93,7 @@ public class HttpClientMultipartLiveTest {
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine() final int statusCode = response.getStatusLine()
.getStatusCode(); .getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@ -113,10 +104,10 @@ public class HttpClientMultipartLiveTest {
} }
@Test @Test
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME); .getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath()); final File file = new File(url.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -127,7 +118,7 @@ public class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine() final int statusCode = response.getStatusLine()
.getStatusCode(); .getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@ -138,13 +129,13 @@ public class HttpClientMultipartLiveTest {
} }
@Test @Test
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + ZIPFILENAME); .getResource("uploads/" + ZIPFILENAME);
final URL url2 = Thread.currentThread() final URL url2 = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + IMAGEFILENAME); .getResource("uploads/" + IMAGEFILENAME);
final InputStream inputStream = new FileInputStream(url.getPath()); final InputStream inputStream = new FileInputStream(url.getPath());
final File file = new File(url2.getPath()); final File file = new File(url2.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
@ -157,7 +148,7 @@ public class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine() final int statusCode = response.getStatusLine()
.getStatusCode(); .getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest {
} }
@Test @Test
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final byte[] bytes = "binary code".getBytes(); final byte[] bytes = "binary code".getBytes();
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -180,7 +171,7 @@ public class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine() final int statusCode = response.getStatusLine()
.getStatusCode(); .getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@ -192,21 +183,21 @@ public class HttpClientMultipartLiveTest {
// UTIL // UTIL
final String getContent() throws IOException { private String getContent() throws IOException {
rd = new BufferedReader(new InputStreamReader(response.getEntity() rd = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent())); .getContent()));
String body = ""; String body = "";
String content = ""; StringBuilder content = new StringBuilder();
while ((body = rd.readLine()) != null) { while ((body = rd.readLine()) != null) {
content += body + "\n"; content.append(body).append("\n");
} }
return content.trim(); return content.toString().trim();
} }
final String getContentTypeHeader() throws IOException { private String getContentTypeHeader() throws IOException {
return post.getEntity() return post.getEntity()
.getContentType() .getContentType()
.toString(); .toString();
} }
} }

View File

@ -1,20 +1,10 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Request;
@ -29,6 +19,15 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.junit.Test; import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
/* /*
* NOTE : Need module spring-rest to be running * NOTE : Need module spring-rest to be running
*/ */
@ -39,7 +38,7 @@ public class HttpClientPostingLiveTest {
private static final String DEFAULT_PASS = "test"; private static final String DEFAULT_PASS = "test";
@Test @Test
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault(); final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL); final HttpPost httpPost = new HttpPost(SAMPLE_URL);
@ -54,7 +53,7 @@ public class HttpClientPostingLiveTest {
} }
@Test @Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
final CloseableHttpClient client = HttpClients.createDefault(); final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
@ -68,7 +67,7 @@ public class HttpClientPostingLiveTest {
} }
@Test @Test
public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault(); final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail"); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
@ -84,14 +83,14 @@ public class HttpClientPostingLiveTest {
} }
@Test @Test
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} }
@Test @Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault(); final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart"); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
@ -109,7 +108,7 @@ public class HttpClientPostingLiveTest {
} }
@Test @Test
public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault(); final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
@ -125,7 +124,7 @@ public class HttpClientPostingLiveTest {
} }
@Test @Test
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault(); final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
@ -133,12 +132,7 @@ public class HttpClientPostingLiveTest {
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build(); final HttpEntity multipart = builder.build();
final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() { final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
@Override
public void progress(final float percentage) {
assertFalse(Float.compare(percentage, 100) > 0);
}
};
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));

View File

@ -1,13 +1,5 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpHead;
@ -21,6 +13,12 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; 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 { public class HttpClientRedirectLiveTest {
private CloseableHttpClient instance; private CloseableHttpClient instance;
@ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests
@Test @Test
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
instance = HttpClients.custom().disableRedirectHandling().build(); instance = HttpClients.custom().disableRedirectHandling().build();
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw"); final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
@ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest {
} }
@Test @Test
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
instance = HttpClientBuilder.create().disableRedirectHandling().build(); instance = HttpClientBuilder.create().disableRedirectHandling().build();
response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw")); response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
@ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest {
// redirect with POST // redirect with POST
@Test @Test
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
instance = HttpClientBuilder.create().build(); instance = HttpClientBuilder.create().build();
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
} }
@Test @Test
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
/** Redirectable methods. */ /** Redirectable methods. */
private final String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME }; private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
@Override @Override
protected boolean isRedirectable(final String method) { protected boolean isRedirectable(final String method) {
for (final String m : REDIRECT_METHODS) { return Arrays.stream(REDIRECT_METHODS)
if (m.equalsIgnoreCase(method)) { .anyMatch(m -> m.equalsIgnoreCase(method));
return true;
}
}
return false;
} }
}).build(); }).build();
@ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest {
} }
@Test @Test
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
@ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest {
} }
@Test @Test
public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

View File

@ -1,13 +1,5 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -18,31 +10,24 @@ import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class HttpClientTimeoutLiveTest { public class HttpClientTimeoutLiveTest {
private CloseableHttpResponse response; private CloseableHttpResponse response;
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests
@Test @Test
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException { public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
final int timeout = 2; final int timeout = 2;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
@ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest {
} }
@Test @Test
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException { public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException {
final int timeout = 2; final int timeout = 2;
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build(); final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
@ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest {
} }
@Test @Test
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException { public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException {
final int timeout = 5; final int timeout = 5;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
@ -87,7 +72,7 @@ public class HttpClientTimeoutLiveTest {
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP) * This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
*/ */
@Test(expected = HttpHostConnectException.class) @Test(expected = HttpHostConnectException.class)
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException { public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
final int timeout = 3; final int timeout = 3;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();

View File

@ -1,14 +1,5 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
@ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.SSLContexts;
import org.junit.Test; import org.junit.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/** /**
* This test requires a localhost server over HTTPS <br> * This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build * It should only be manually run, not part of the automated build

View File

@ -10,7 +10,7 @@ import org.apache.http.entity.HttpEntityWrapper;
public class ProgressEntityWrapper extends HttpEntityWrapper { public class ProgressEntityWrapper extends HttpEntityWrapper {
private final ProgressListener listener; private final ProgressListener listener;
public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
super(entity); super(entity);
this.listener = listener; this.listener = listener;
} }
@ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper {
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
} }
public static interface ProgressListener { public interface ProgressListener {
void progress(float percentage); void progress(float percentage);
} }
@ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper {
private long transferred; private long transferred;
private long totalBytes; private long totalBytes;
public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
super(out); super(out);
this.listener = listener; this.listener = listener;
transferred = 0; transferred = 0;

View File

@ -0,0 +1,26 @@
package org.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();
}
}
}

View File

@ -24,7 +24,14 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.*; 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; import static org.junit.Assert.assertEquals;
public class HttpClientAdvancedConfigurationIntegrationTest { public class HttpClientAdvancedConfigurationIntegrationTest {
@ -40,9 +47,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
//given //given
String userAgent = "BaeldungAgent/1.0"; String userAgent = "BaeldungAgent/1.0";
serviceMock.stubFor(get(urlEqualTo("/detail")) serviceMock.stubFor(get(urlEqualTo("/detail"))
.withHeader("User-Agent", equalTo(userAgent)) .withHeader("User-Agent", equalTo(userAgent))
.willReturn(aResponse() .willReturn(aResponse()
.withStatus(200))); .withStatus(200)));
HttpClient httpClient = HttpClients.createDefault(); HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); HttpGet httpGet = new HttpGet("http://localhost:8089/detail");
@ -60,10 +67,10 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
//given //given
String xmlBody = "<xml><id>1</id></xml>"; String xmlBody = "<xml><id>1</id></xml>";
serviceMock.stubFor(post(urlEqualTo("/person")) serviceMock.stubFor(post(urlEqualTo("/person"))
.withHeader("Content-Type", equalTo("application/xml")) .withHeader("Content-Type", equalTo("application/xml"))
.withRequestBody(equalTo(xmlBody)) .withRequestBody(equalTo(xmlBody))
.willReturn(aResponse() .willReturn(aResponse()
.withStatus(200))); .withStatus(200)));
HttpClient httpClient = HttpClients.createDefault(); HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8089/person"); HttpPost httpPost = new HttpPost("http://localhost:8089/person");
@ -83,17 +90,17 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
//given //given
proxyMock.stubFor(get(urlMatching(".*")) proxyMock.stubFor(get(urlMatching(".*"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); .willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
serviceMock.stubFor(get(urlEqualTo("/private")) serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200))); .willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090); HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
HttpClient httpclient = HttpClients.custom() HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner) .setRoutePlanner(routePlanner)
.build(); .build();
//when //when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
@ -109,9 +116,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
//given //given
proxyMock.stubFor(get(urlMatching("/private")) proxyMock.stubFor(get(urlMatching("/private"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); .willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
serviceMock.stubFor(get(urlEqualTo("/private")) serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200))); .willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090); HttpHost proxy = new HttpHost("localhost", 8090);
@ -120,7 +127,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
// Client credentials // Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy), credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password")); new UsernamePasswordCredentials("username_admin", "secret_password"));
// Create AuthCache instance // Create AuthCache instance
@ -135,9 +142,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpClient httpclient = HttpClients.custom() HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner) .setRoutePlanner(routePlanner)
.setDefaultCredentialsProvider(credentialsProvider) .setDefaultCredentialsProvider(credentialsProvider)
.build(); .build();
//when //when

View File

@ -1,13 +1,5 @@
package org.baeldung.httpclient.base; package org.baeldung.httpclient.base;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
@ -16,10 +8,17 @@ import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.baeldung.httpclient.ResponseUtil;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class HttpClientBasicLiveTest { public class HttpClientBasicLiveTest {
private static final String SAMPLE_URL = "http://www.github.com"; private static final String SAMPLE_URL = "http://www.github.com";
@ -35,19 +34,7 @@ public class HttpClientBasicLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests

View File

@ -1,22 +1,20 @@
package org.baeldung.httpclient.base; package org.baeldung.httpclient.base;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.baeldung.httpclient.ResponseUtil;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
public class HttpClientBasicPostLiveTest { public class HttpClientBasicPostLiveTest {
private static final String SAMPLE_URL = "http://www.github.com"; private static final String SAMPLE_URL = "http://www.github.com";
@ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests - non-GET // tests - non-GET
@Test @Test
public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException { public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
instance.execute(new HttpPost(SAMPLE_URL)); instance.execute(new HttpPost(SAMPLE_URL));
} }
@Test @Test
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException { public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
final HttpPost request = new HttpPost(SAMPLE_URL); final HttpPost request = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity("in the body of the POST")); request.setEntity(new StringEntity("in the body of the POST"));
instance.execute(request); instance.execute(request);
} }
@Test @Test
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException { public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
final HttpPost request = new HttpPost(SAMPLE_URL); final HttpPost request = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity("in the body of the POST")); request.setEntity(new StringEntity("in the body of the POST"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");

View File

@ -11,12 +11,12 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.baeldung.httpclient.ResponseUtil;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
@ -37,19 +37,7 @@ public class HttpClientLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests

View File

@ -1,9 +1,5 @@
package org.baeldung.httpclient.base; package org.baeldung.httpclient.base;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
@ -12,8 +8,11 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.baeldung.httpclient.ResponseUtil;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
/* /*
* NOTE : Need module spring-security-rest-basic-auth to be running * NOTE : Need module spring-security-rest-basic-auth to be running
*/ */
@ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest {
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
try { ResponseUtil.closeResponse(response);
final HttpEntity entity = response.getEntity();
if (entity != null) {
// EntityUtils.consume(entity);
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
} }

View File

@ -1,11 +1,5 @@
package org.baeldung.httpclient.conn; package org.baeldung.httpclient.conn;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HeaderElement; import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator; import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpClientConnection; import org.apache.http.HttpClientConnection;
@ -36,6 +30,12 @@ import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertTrue;
public class HttpClientConnectionManagementLiveTest { public class HttpClientConnectionManagementLiveTest {
private static final String SERVER1 = "http://www.petrikainulainen.net/"; private static final String SERVER1 = "http://www.petrikainulainen.net/";
private static final String SERVER7 = "http://www.baeldung.com/"; private static final String SERVER7 = "http://www.baeldung.com/";
@ -129,7 +129,7 @@ public class HttpClientConnectionManagementLiveTest {
@Test @Test
// @Ignore // @Ignore
// Example 3.2. TESTER VERSION // Example 3.2. TESTER VERSION
/*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { /*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager = new PoolingHttpClientConnectionManager();
final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build();
final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build();
@ -173,7 +173,7 @@ public class HttpClientConnectionManagementLiveTest {
@Test @Test
// @Ignore // @Ignore
// 4.2 Tester Version // 4.2 Tester Version
/*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { /*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException {
poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager = new PoolingHttpClientConnectionManager();
client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
@ -266,7 +266,7 @@ public class HttpClientConnectionManagementLiveTest {
@Test @Test
// @Ignore // @Ignore
// 6.2 TESTER VERSION // 6.2 TESTER VERSION
/*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { /*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager = new PoolingHttpClientConnectionManager();
poolingConnManager.setDefaultMaxPerRoute(5); poolingConnManager.setDefaultMaxPerRoute(5);
poolingConnManager.setMaxTotal(5); poolingConnManager.setMaxTotal(5);
@ -333,7 +333,7 @@ public class HttpClientConnectionManagementLiveTest {
@Test @Test
@Ignore("Very Long Running") @Ignore("Very Long Running")
// 8.2 TESTER VERSION // 8.2 TESTER VERSION
/*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { /*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException {
poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager = new PoolingHttpClientConnectionManager();
client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);

View File

@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr; private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown; private volatile boolean shutdown;
public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
super(); super();
this.connMgr = connMgr; this.connMgr = connMgr;
} }
@ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread {
} }
} }
public final void shutdown() { private void shutdown() {
shutdown = true; shutdown = true;
synchronized (this) { synchronized (this) {
notifyAll(); notifyAll();

View File

@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread {
private final HttpGet get; private final HttpGet get;
private PoolingHttpClientConnectionManager connManager; private PoolingHttpClientConnectionManager connManager;
public int leasedConn; private int leasedConn;
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
this.client = client; this.client = client;
this.get = get; this.get = get;
this.connManager = connManager; this.connManager = connManager;
leasedConn = 0; leasedConn = 0;
} }
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
this.client = client; this.client = client;
this.get = get; this.get = get;
} }
// API // API
public final int getLeasedConn() { final int getLeasedConn() {
return leasedConn; return leasedConn;
} }
@ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread {
} }
EntityUtils.consume(response.getEntity()); EntityUtils.consume(response.getEntity());
} catch (final ClientProtocolException ex) {
logger.error("", ex);
} catch (final IOException ex) { } catch (final IOException ex) {
logger.error("", ex); logger.error("", ex);
} }

View File

@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread {
private final HttpGet get; private final HttpGet get;
private PoolingHttpClientConnectionManager connManager; private PoolingHttpClientConnectionManager connManager;
public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
this.client = client; this.client = client;
this.get = get; this.get = get;
this.connManager = Preconditions.checkNotNull(connManager); this.connManager = Preconditions.checkNotNull(connManager);
@ -38,8 +38,6 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread {
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
} catch (final ClientProtocolException ex) {
logger.error("", ex);
} catch (final IOException ex) { } catch (final IOException ex) {
logger.error("", ex); logger.error("", ex);
} }

View File

@ -1,12 +1,7 @@
package org.baeldung.httpclient.rare; package org.baeldung.httpclient.rare;
import static org.hamcrest.Matchers.equalTo; import com.google.common.base.Preconditions;
import static org.junit.Assert.assertThat; import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.Header; import org.apache.http.Header;
@ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.google.common.base.Preconditions; import java.io.IOException;
import com.google.common.collect.Lists; import java.io.InputStream;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class HttpClientUnshortenLiveTest { public class HttpClientUnshortenLiveTest {
@ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest {
// API // API
final String expand(final String urlArg) throws IOException { private String expand(final String urlArg) throws IOException {
String originalUrl = urlArg; String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl); String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) { while (!originalUrl.equals(newUrl)) {
@ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest {
return newUrl; return newUrl;
} }
final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException { private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
HttpHead request = null; HttpHead request = null;
HttpEntity httpEntity = null; HttpEntity httpEntity = null;
InputStream entityContentStream = null; InputStream entityContentStream = null;
@ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest {
final int statusCode = httpResponse.getStatusLine().getStatusCode(); final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) { if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<Integer, String>(statusCode, url); return new ImmutablePair<>(statusCode, url);
} }
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1); Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue(); final String newUrl = headers[0].getValue();
return new ImmutablePair<Integer, String>(statusCode, newUrl); return new ImmutablePair<>(statusCode, newUrl);
} catch (final IllegalArgumentException uriEx) { } catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<Integer, String>(500, url); return new ImmutablePair<>(500, url);
} finally { } finally {
if (request != null) { if (request != null) {
request.releaseConnection(); request.releaseConnection();
@ -117,7 +116,7 @@ public class HttpClientUnshortenLiveTest {
} }
} }
final String expandSingleLevel(final String url) throws IOException { private String expandSingleLevel(final String url) throws IOException {
HttpHead request = null; HttpHead request = null;
try { try {
@ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest {
} }
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1); Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
return newUrl; return headers[0].getValue();
} catch (final IllegalArgumentException uriEx) { } catch (final IllegalArgumentException uriEx) {
return url; return url;
} finally { } finally {

View File

@ -1,21 +1,12 @@
package org.baeldung.httpclient.sec; package org.baeldung.httpclient.sec;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache; import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -26,10 +17,17 @@ import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.baeldung.httpclient.ResponseUtil;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/* /*
* NOTE : Need module spring-security-rest-basic-auth to be running * NOTE : Need module spring-security-rest-basic-auth to be running
*/ */
@ -51,25 +49,13 @@ public class HttpClientAuthLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests
@Test @Test
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
@ -79,7 +65,7 @@ public class HttpClientAuthLiveTest {
} }
@Test @Test
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
client = HttpClientBuilder.create().build(); client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
@ -88,7 +74,7 @@ public class HttpClientAuthLiveTest {
} }
@Test @Test
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException { public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException {
client = HttpClientBuilder.create().build(); client = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
@ -100,7 +86,7 @@ public class HttpClientAuthLiveTest {
} }
@Test @Test
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException { public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
@ -116,14 +102,14 @@ public class HttpClientAuthLiveTest {
// UTILS // UTILS
private final CredentialsProvider provider() { private CredentialsProvider provider() {
final CredentialsProvider provider = new BasicCredentialsProvider(); final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, credentials); provider.setCredentials(AuthScope.ANY, credentials);
return provider; return provider;
} }
private final HttpContext context() { private HttpContext context() {
final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
@ -141,12 +127,11 @@ public class HttpClientAuthLiveTest {
return context; return context;
} }
private final String authorizationHeader(final String username, final String password) { private String authorizationHeader(final String username, final String password) {
final String auth = username + ":" + password; final String auth = username + ":" + password;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
final String authHeader = "Basic " + new String(encodedAuth);
return authHeader; return "Basic " + new String(encodedAuth);
} }
} }

View File

@ -1,13 +1,5 @@
package org.baeldung.httpclient.sec; package org.baeldung.httpclient.sec;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -18,10 +10,16 @@ import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.baeldung.httpclient.ResponseUtil;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class HttpClientCookieLiveTest { public class HttpClientCookieLiveTest {
private CloseableHttpClient instance; private CloseableHttpClient instance;
@ -35,25 +33,13 @@ public class HttpClientCookieLiveTest {
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { ResponseUtil.closeResponse(response);
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
} }
// tests // tests
@Test @Test
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException { public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException {
instance = HttpClientBuilder.create().build(); instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com"); final HttpGet request = new HttpGet("http://www.github.com");
request.setHeader("Cookie", "JSESSIONID=1234"); request.setHeader("Cookie", "JSESSIONID=1234");
@ -64,7 +50,7 @@ public class HttpClientCookieLiveTest {
} }
@Test @Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException { public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
@ -80,7 +66,7 @@ public class HttpClientCookieLiveTest {
} }
@Test @Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException { public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
@ -96,7 +82,7 @@ public class HttpClientCookieLiveTest {
} }
@Test @Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException { public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");