Skip to content

Commit ffd66fa

Browse files
authoredJul 19, 2017
Refactor HttpClient (eugenp#2272)
1 parent 14456eb commit ffd66fa

21 files changed

+230
-350
lines changed
 

‎httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java

+2-7
Original file line numberDiff line numberDiff line change
@@ -101,12 +101,7 @@ public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
101101

102102
@Test
103103
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
104-
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
105-
@Override
106-
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
107-
return true;
108-
}
109-
};
104+
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
110105
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
111106

112107
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build();
@@ -160,7 +155,7 @@ static class GetThread extends Thread {
160155
private final HttpContext context;
161156
private final HttpGet request;
162157

163-
public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
158+
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
164159
this.client = client;
165160
context = HttpClientContext.create();
166161
this.request = request;

‎httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java

+4-19
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
package org.baeldung.httpclient;
22

3-
import java.io.IOException;
4-
import java.io.InputStream;
5-
import java.util.List;
6-
3+
import com.google.common.collect.Lists;
74
import org.apache.http.Header;
8-
import org.apache.http.HttpEntity;
95
import org.apache.http.HttpHeaders;
106
import org.apache.http.client.ClientProtocolException;
117
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -20,7 +16,8 @@
2016
import org.junit.Before;
2117
import org.junit.Test;
2218

23-
import com.google.common.collect.Lists;
19+
import java.io.IOException;
20+
import java.util.List;
2421

2522
public class HttpClientHeadersLiveTest {
2623

@@ -37,19 +34,7 @@ public final void before() {
3734

3835
@After
3936
public final void after() throws IllegalStateException, IOException {
40-
if (response == null) {
41-
return;
42-
}
43-
44-
try {
45-
final HttpEntity entity = response.getEntity();
46-
if (entity != null) {
47-
final InputStream instream = entity.getContent();
48-
instream.close();
49-
}
50-
} finally {
51-
response.close();
52-
}
37+
ResponseUtil.closeResponse(response);
5338
}
5439

5540
// tests - headers - deprecated

‎httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java

+39-48
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,7 @@
11
package org.baeldung.httpclient;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
import static org.junit.Assert.assertTrue;
6-
7-
import java.io.BufferedReader;
8-
import java.io.File;
9-
import java.io.FileInputStream;
10-
import java.io.IOException;
11-
import java.io.InputStream;
12-
import java.io.InputStreamReader;
13-
import java.net.URL;
14-
import java.util.logging.Level;
15-
import java.util.logging.Logger;
16-
173
import org.apache.http.HttpEntity;
184
import org.apache.http.HttpStatus;
19-
import org.apache.http.client.ClientProtocolException;
205
import org.apache.http.client.methods.CloseableHttpResponse;
216
import org.apache.http.client.methods.HttpPost;
227
import org.apache.http.entity.ContentType;
@@ -30,6 +15,20 @@
3015
import org.junit.Before;
3116
import org.junit.Test;
3217

18+
import java.io.BufferedReader;
19+
import java.io.File;
20+
import java.io.FileInputStream;
21+
import java.io.IOException;
22+
import java.io.InputStream;
23+
import java.io.InputStreamReader;
24+
import java.net.URL;
25+
import java.util.logging.Level;
26+
import java.util.logging.Logger;
27+
28+
import static org.hamcrest.Matchers.equalTo;
29+
import static org.junit.Assert.assertThat;
30+
import static org.junit.Assert.assertTrue;
31+
3332
public class HttpClientMultipartLiveTest {
3433

3534
// No longer available
@@ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest {
4847
@Before
4948
public final void before() {
5049
client = HttpClientBuilder.create()
51-
.build();
50+
.build();
5251
post = new HttpPost(SERVER);
5352
}
5453

@@ -67,24 +66,16 @@ public final void after() throws IllegalStateException, IOException {
6766
LOGGER.log(Level.SEVERE, e.getMessage(), e);
6867
throw e;
6968
}
70-
try {
71-
final HttpEntity entity = response.getEntity();
72-
if (entity != null) {
73-
final InputStream instream = entity.getContent();
74-
instream.close();
75-
}
76-
} finally {
77-
response.close();
78-
}
69+
ResponseUtil.closeResponse(response);
7970
}
8071

8172
// tests
8273

8374
@Test
8475
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
8576
final URL url = Thread.currentThread()
86-
.getContextClassLoader()
87-
.getResource("uploads/" + TEXTFILENAME);
77+
.getContextClassLoader()
78+
.getResource("uploads/" + TEXTFILENAME);
8879

8980
final File file = new File(url.getPath());
9081
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
@@ -102,7 +93,7 @@ public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExce
10293
response = client.execute(post);
10394

10495
final int statusCode = response.getStatusLine()
105-
.getStatusCode();
96+
.getStatusCode();
10697
final String responseString = getContent();
10798
final String contentTypeInHeader = getContentTypeHeader();
10899
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@@ -113,10 +104,10 @@ public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExce
113104
}
114105

115106
@Test
116-
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
107+
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
117108
final URL url = Thread.currentThread()
118-
.getContextClassLoader()
119-
.getResource("uploads/" + TEXTFILENAME);
109+
.getContextClassLoader()
110+
.getResource("uploads/" + TEXTFILENAME);
120111
final File file = new File(url.getPath());
121112
final String message = "This is a multipart post";
122113
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@@ -127,7 +118,7 @@ public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody
127118
post.setEntity(entity);
128119
response = client.execute(post);
129120
final int statusCode = response.getStatusLine()
130-
.getStatusCode();
121+
.getStatusCode();
131122
final String responseString = getContent();
132123
final String contentTypeInHeader = getContentTypeHeader();
133124
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@@ -138,13 +129,13 @@ public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody
138129
}
139130

140131
@Test
141-
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
132+
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
142133
final URL url = Thread.currentThread()
143-
.getContextClassLoader()
144-
.getResource("uploads/" + ZIPFILENAME);
134+
.getContextClassLoader()
135+
.getResource("uploads/" + ZIPFILENAME);
145136
final URL url2 = Thread.currentThread()
146-
.getContextClassLoader()
147-
.getResource("uploads/" + IMAGEFILENAME);
137+
.getContextClassLoader()
138+
.getResource("uploads/" + IMAGEFILENAME);
148139
final InputStream inputStream = new FileInputStream(url.getPath());
149140
final File file = new File(url2.getPath());
150141
final String message = "This is a multipart post";
@@ -157,7 +148,7 @@ public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandA
157148
post.setEntity(entity);
158149
response = client.execute(post);
159150
final int statusCode = response.getStatusLine()
160-
.getStatusCode();
151+
.getStatusCode();
161152
final String responseString = getContent();
162153
final String contentTypeInHeader = getContentTypeHeader();
163154
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@@ -169,7 +160,7 @@ public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandA
169160
}
170161

171162
@Test
172-
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
163+
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
173164
final String message = "This is a multipart post";
174165
final byte[] bytes = "binary code".getBytes();
175166
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@@ -180,7 +171,7 @@ public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBod
180171
post.setEntity(entity);
181172
response = client.execute(post);
182173
final int statusCode = response.getStatusLine()
183-
.getStatusCode();
174+
.getStatusCode();
184175
final String responseString = getContent();
185176
final String contentTypeInHeader = getContentTypeHeader();
186177
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
@@ -192,21 +183,21 @@ public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBod
192183

193184
// UTIL
194185

195-
final String getContent() throws IOException {
186+
private String getContent() throws IOException {
196187
rd = new BufferedReader(new InputStreamReader(response.getEntity()
197-
.getContent()));
188+
.getContent()));
198189
String body = "";
199-
String content = "";
190+
StringBuilder content = new StringBuilder();
200191
while ((body = rd.readLine()) != null) {
201-
content += body + "\n";
192+
content.append(body).append("\n");
202193
}
203-
return content.trim();
194+
return content.toString().trim();
204195
}
205196

206-
final String getContentTypeHeader() throws IOException {
197+
private String getContentTypeHeader() throws IOException {
207198
return post.getEntity()
208-
.getContentType()
209-
.toString();
199+
.getContentType()
200+
.toString();
210201
}
211202

212203
}

‎httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java

+17-23
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,10 @@
11
package org.baeldung.httpclient;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertFalse;
5-
import static org.junit.Assert.assertThat;
6-
7-
import java.io.File;
8-
import java.io.IOException;
9-
import java.util.ArrayList;
10-
import java.util.List;
11-
123
import org.apache.http.HttpEntity;
134
import org.apache.http.HttpResponse;
145
import org.apache.http.NameValuePair;
156
import org.apache.http.auth.AuthenticationException;
167
import org.apache.http.auth.UsernamePasswordCredentials;
17-
import org.apache.http.client.ClientProtocolException;
188
import org.apache.http.client.entity.UrlEncodedFormEntity;
199
import org.apache.http.client.fluent.Form;
2010
import org.apache.http.client.fluent.Request;
@@ -29,6 +19,15 @@
2919
import org.apache.http.message.BasicNameValuePair;
3020
import org.junit.Test;
3121

22+
import java.io.File;
23+
import java.io.IOException;
24+
import java.util.ArrayList;
25+
import java.util.List;
26+
27+
import static org.hamcrest.Matchers.equalTo;
28+
import static org.junit.Assert.assertFalse;
29+
import static org.junit.Assert.assertThat;
30+
3231
/*
3332
* NOTE : Need module spring-rest to be running
3433
*/
@@ -39,7 +38,7 @@ public class HttpClientPostingLiveTest {
3938
private static final String DEFAULT_PASS = "test";
4039

4140
@Test
42-
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
41+
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
4342
final CloseableHttpClient client = HttpClients.createDefault();
4443
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
4544

@@ -54,7 +53,7 @@ public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtoc
5453
}
5554

5655
@Test
57-
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException {
56+
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
5857
final CloseableHttpClient client = HttpClients.createDefault();
5958
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
6059

@@ -68,7 +67,7 @@ public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() th
6867
}
6968

7069
@Test
71-
public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
70+
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
7271
final CloseableHttpClient client = HttpClients.createDefault();
7372
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
7473

@@ -84,14 +83,14 @@ public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolExcep
8483
}
8584

8685
@Test
87-
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException {
86+
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
8887
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
8988

9089
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
9190
}
9291

9392
@Test
94-
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
93+
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
9594
final CloseableHttpClient client = HttpClients.createDefault();
9695
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
9796

@@ -109,7 +108,7 @@ public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientP
109108
}
110109

111110
@Test
112-
public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
111+
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
113112
final CloseableHttpClient client = HttpClients.createDefault();
114113
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
115114

@@ -125,20 +124,15 @@ public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolExc
125124
}
126125

127126
@Test
128-
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
127+
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
129128
final CloseableHttpClient client = HttpClients.createDefault();
130129
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
131130

132131
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
133132
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
134133
final HttpEntity multipart = builder.build();
135134

136-
final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() {
137-
@Override
138-
public void progress(final float percentage) {
139-
assertFalse(Float.compare(percentage, 100) > 0);
140-
}
141-
};
135+
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
142136

143137
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
144138

‎httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java

+16-34
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
package org.baeldung.httpclient;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
6-
import java.io.IOException;
7-
import java.io.InputStream;
8-
9-
import org.apache.http.HttpEntity;
10-
import org.apache.http.client.ClientProtocolException;
113
import org.apache.http.client.methods.CloseableHttpResponse;
124
import org.apache.http.client.methods.HttpGet;
135
import org.apache.http.client.methods.HttpHead;
@@ -21,6 +13,12 @@
2113
import org.junit.Before;
2214
import org.junit.Test;
2315

16+
import java.io.IOException;
17+
import java.util.Arrays;
18+
19+
import static org.hamcrest.Matchers.equalTo;
20+
import static org.junit.Assert.assertThat;
21+
2422
public class HttpClientRedirectLiveTest {
2523

2624
private CloseableHttpClient instance;
@@ -34,25 +32,13 @@ public final void before() {
3432

3533
@After
3634
public final void after() throws IllegalStateException, IOException {
37-
if (response == null) {
38-
return;
39-
}
40-
41-
try {
42-
final HttpEntity entity = response.getEntity();
43-
if (entity != null) {
44-
final InputStream instream = entity.getContent();
45-
instream.close();
46-
}
47-
} finally {
48-
response.close();
49-
}
35+
ResponseUtil.closeResponse(response);
5036
}
5137

5238
// tests
5339

5440
@Test
55-
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
41+
public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
5642
instance = HttpClients.custom().disableRedirectHandling().build();
5743

5844
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
@@ -62,7 +48,7 @@ public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedire
6248
}
6349

6450
@Test
65-
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
51+
public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
6652
instance = HttpClientBuilder.create().disableRedirectHandling().build();
6753
response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
6854
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
@@ -71,26 +57,22 @@ public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenN
7157
// redirect with POST
7258

7359
@Test
74-
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException {
60+
public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
7561
instance = HttpClientBuilder.create().build();
7662
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
7763
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
7864
}
7965

8066
@Test
81-
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException {
67+
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
8268
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
8369
/** Redirectable methods. */
84-
private final String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME };
70+
private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
8571

8672
@Override
8773
protected boolean isRedirectable(final String method) {
88-
for (final String m : REDIRECT_METHODS) {
89-
if (m.equalsIgnoreCase(method)) {
90-
return true;
91-
}
92-
}
93-
return false;
74+
return Arrays.stream(REDIRECT_METHODS)
75+
.anyMatch(m -> m.equalsIgnoreCase(method));
9476
}
9577
}).build();
9678

@@ -99,15 +81,15 @@ protected boolean isRedirectable(final String method) {
9981
}
10082

10183
@Test
102-
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException {
84+
public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
10385
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build();
10486

10587
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
10688
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
10789
}
10890

10991
@Test
110-
public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException {
92+
public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
11193
instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
11294
response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
11395
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

‎httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java

+10-25
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
package org.baeldung.httpclient;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
6-
import java.io.IOException;
7-
import java.io.InputStream;
8-
9-
import org.apache.http.HttpEntity;
10-
import org.apache.http.client.ClientProtocolException;
113
import org.apache.http.client.config.RequestConfig;
124
import org.apache.http.client.methods.CloseableHttpResponse;
135
import org.apache.http.client.methods.HttpGet;
@@ -18,31 +10,24 @@
1810
import org.junit.After;
1911
import org.junit.Test;
2012

13+
import java.io.IOException;
14+
15+
import static org.hamcrest.Matchers.equalTo;
16+
import static org.junit.Assert.assertThat;
17+
2118
public class HttpClientTimeoutLiveTest {
2219

2320
private CloseableHttpResponse response;
2421

2522
@After
2623
public final void after() throws IllegalStateException, IOException {
27-
if (response == null) {
28-
return;
29-
}
30-
31-
try {
32-
final HttpEntity entity = response.getEntity();
33-
if (entity != null) {
34-
final InputStream instream = entity.getContent();
35-
instream.close();
36-
}
37-
} finally {
38-
response.close();
39-
}
24+
ResponseUtil.closeResponse(response);
4025
}
4126

4227
// tests
4328

4429
@Test
45-
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException {
30+
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
4631
final int timeout = 2;
4732
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
4833
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
@@ -56,7 +41,7 @@ public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrec
5641
}
5742

5843
@Test
59-
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException {
44+
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException {
6045
final int timeout = 2;
6146

6247
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
@@ -70,7 +55,7 @@ public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect
7055
}
7156

7257
@Test
73-
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException {
58+
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException {
7459
final int timeout = 5;
7560

7661
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
@@ -87,7 +72,7 @@ public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect
8772
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
8873
*/
8974
@Test(expected = HttpHostConnectException.class)
90-
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException {
75+
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
9176
final int timeout = 3;
9277

9378
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();

‎httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java

+8-9
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,5 @@
11
package org.baeldung.httpclient;
22

3-
import static org.hamcrest.CoreMatchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
6-
import java.io.IOException;
7-
import java.security.GeneralSecurityException;
8-
9-
import javax.net.ssl.SSLContext;
10-
import javax.net.ssl.SSLHandshakeException;
11-
123
import org.apache.http.HttpResponse;
134
import org.apache.http.client.methods.HttpGet;
145
import org.apache.http.conn.ClientConnectionManager;
@@ -28,6 +19,14 @@
2819
import org.apache.http.ssl.SSLContexts;
2920
import org.junit.Test;
3021

22+
import javax.net.ssl.SSLContext;
23+
import javax.net.ssl.SSLHandshakeException;
24+
import java.io.IOException;
25+
import java.security.GeneralSecurityException;
26+
27+
import static org.hamcrest.CoreMatchers.equalTo;
28+
import static org.junit.Assert.assertThat;
29+
3130
/**
3231
* This test requires a localhost server over HTTPS <br>
3332
* It should only be manually run, not part of the automated build

‎httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
public class ProgressEntityWrapper extends HttpEntityWrapper {
1111
private final ProgressListener listener;
1212

13-
public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
13+
ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
1414
super(entity);
1515
this.listener = listener;
1616
}
@@ -20,7 +20,7 @@ public void writeTo(final OutputStream outstream) throws IOException {
2020
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
2121
}
2222

23-
public static interface ProgressListener {
23+
public interface ProgressListener {
2424
void progress(float percentage);
2525
}
2626

@@ -30,7 +30,7 @@ public static class CountingOutputStream extends FilterOutputStream {
3030
private long transferred;
3131
private long totalBytes;
3232

33-
public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
33+
CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
3434
super(out);
3535
this.listener = listener;
3636
transferred = 0;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package org.baeldung.httpclient;
2+
3+
import org.apache.http.HttpEntity;
4+
import org.apache.http.client.methods.CloseableHttpResponse;
5+
6+
import java.io.IOException;
7+
8+
public final class ResponseUtil {
9+
private ResponseUtil() {
10+
}
11+
12+
public static void closeResponse(CloseableHttpResponse response) throws IOException {
13+
if (response == null) {
14+
return;
15+
}
16+
17+
try {
18+
final HttpEntity entity = response.getEntity();
19+
if (entity != null) {
20+
entity.getContent().close();
21+
}
22+
} finally {
23+
response.close();
24+
}
25+
}
26+
}

‎httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java

+25-18
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,14 @@
2424

2525
import java.io.IOException;
2626

27-
import static com.github.tomakehurst.wiremock.client.WireMock.*;
27+
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
28+
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
29+
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
30+
import static com.github.tomakehurst.wiremock.client.WireMock.get;
31+
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
32+
import static com.github.tomakehurst.wiremock.client.WireMock.post;
33+
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
34+
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
2835
import static org.junit.Assert.assertEquals;
2936

3037
public class HttpClientAdvancedConfigurationIntegrationTest {
@@ -40,9 +47,9 @@ public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn
4047
//given
4148
String userAgent = "BaeldungAgent/1.0";
4249
serviceMock.stubFor(get(urlEqualTo("/detail"))
43-
.withHeader("User-Agent", equalTo(userAgent))
44-
.willReturn(aResponse()
45-
.withStatus(200)));
50+
.withHeader("User-Agent", equalTo(userAgent))
51+
.willReturn(aResponse()
52+
.withStatus(200)));
4653

4754
HttpClient httpClient = HttpClients.createDefault();
4855
HttpGet httpGet = new HttpGet("http://localhost:8089/detail");
@@ -60,10 +67,10 @@ public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() th
6067
//given
6168
String xmlBody = "<xml><id>1</id></xml>";
6269
serviceMock.stubFor(post(urlEqualTo("/person"))
63-
.withHeader("Content-Type", equalTo("application/xml"))
64-
.withRequestBody(equalTo(xmlBody))
65-
.willReturn(aResponse()
66-
.withStatus(200)));
70+
.withHeader("Content-Type", equalTo("application/xml"))
71+
.withRequestBody(equalTo(xmlBody))
72+
.willReturn(aResponse()
73+
.withStatus(200)));
6774

6875
HttpClient httpClient = HttpClients.createDefault();
6976
HttpPost httpPost = new HttpPost("http://localhost:8089/person");
@@ -83,17 +90,17 @@ public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() th
8390
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
8491
//given
8592
proxyMock.stubFor(get(urlMatching(".*"))
86-
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
93+
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
8794

8895
serviceMock.stubFor(get(urlEqualTo("/private"))
89-
.willReturn(aResponse().withStatus(200)));
96+
.willReturn(aResponse().withStatus(200)));
9097

9198

9299
HttpHost proxy = new HttpHost("localhost", 8090);
93100
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
94101
HttpClient httpclient = HttpClients.custom()
95-
.setRoutePlanner(routePlanner)
96-
.build();
102+
.setRoutePlanner(routePlanner)
103+
.build();
97104

98105
//when
99106
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
@@ -109,9 +116,9 @@ public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaP
109116
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
110117
//given
111118
proxyMock.stubFor(get(urlMatching("/private"))
112-
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
119+
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
113120
serviceMock.stubFor(get(urlEqualTo("/private"))
114-
.willReturn(aResponse().withStatus(200)));
121+
.willReturn(aResponse().withStatus(200)));
115122

116123

117124
HttpHost proxy = new HttpHost("localhost", 8090);
@@ -120,7 +127,7 @@ public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shou
120127
// Client credentials
121128
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
122129
credentialsProvider.setCredentials(new AuthScope(proxy),
123-
new UsernamePasswordCredentials("username_admin", "secret_password"));
130+
new UsernamePasswordCredentials("username_admin", "secret_password"));
124131

125132

126133
// Create AuthCache instance
@@ -135,9 +142,9 @@ public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shou
135142

136143

137144
HttpClient httpclient = HttpClients.custom()
138-
.setRoutePlanner(routePlanner)
139-
.setDefaultCredentialsProvider(credentialsProvider)
140-
.build();
145+
.setRoutePlanner(routePlanner)
146+
.setDefaultCredentialsProvider(credentialsProvider)
147+
.build();
141148

142149

143150
//when

‎httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java

+8-21
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
package org.baeldung.httpclient.base;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.hamcrest.Matchers.notNullValue;
5-
import static org.junit.Assert.assertThat;
6-
7-
import java.io.IOException;
8-
import java.io.InputStream;
9-
10-
import org.apache.http.HttpEntity;
113
import org.apache.http.HttpStatus;
124
import org.apache.http.client.ClientProtocolException;
135
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -16,10 +8,17 @@
168
import org.apache.http.impl.client.CloseableHttpClient;
179
import org.apache.http.impl.client.HttpClientBuilder;
1810
import org.apache.http.util.EntityUtils;
11+
import org.baeldung.httpclient.ResponseUtil;
1912
import org.junit.After;
2013
import org.junit.Before;
2114
import org.junit.Test;
2215

16+
import java.io.IOException;
17+
18+
import static org.hamcrest.Matchers.equalTo;
19+
import static org.hamcrest.Matchers.notNullValue;
20+
import static org.junit.Assert.assertThat;
21+
2322
public class HttpClientBasicLiveTest {
2423

2524
private static final String SAMPLE_URL = "http://www.github.com";
@@ -35,19 +34,7 @@ public final void before() {
3534

3635
@After
3736
public final void after() throws IllegalStateException, IOException {
38-
if (response == null) {
39-
return;
40-
}
41-
42-
try {
43-
final HttpEntity entity = response.getEntity();
44-
if (entity != null) {
45-
final InputStream instream = entity.getContent();
46-
instream.close();
47-
}
48-
} finally {
49-
response.close();
50-
}
37+
ResponseUtil.closeResponse(response);
5138
}
5239

5340
// tests

‎httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java

+7-21
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
11
package org.baeldung.httpclient.base;
22

3-
import java.io.IOException;
4-
import java.io.InputStream;
5-
6-
import org.apache.http.HttpEntity;
73
import org.apache.http.auth.AuthenticationException;
84
import org.apache.http.auth.UsernamePasswordCredentials;
9-
import org.apache.http.client.ClientProtocolException;
105
import org.apache.http.client.methods.CloseableHttpResponse;
116
import org.apache.http.client.methods.HttpPost;
127
import org.apache.http.entity.StringEntity;
138
import org.apache.http.impl.auth.BasicScheme;
149
import org.apache.http.impl.client.CloseableHttpClient;
1510
import org.apache.http.impl.client.HttpClientBuilder;
11+
import org.baeldung.httpclient.ResponseUtil;
1612
import org.junit.After;
1713
import org.junit.Before;
1814
import org.junit.Test;
1915

16+
import java.io.IOException;
17+
2018
public class HttpClientBasicPostLiveTest {
2119

2220
private static final String SAMPLE_URL = "http://www.github.com";
@@ -32,37 +30,25 @@ public final void before() {
3230

3331
@After
3432
public final void after() throws IllegalStateException, IOException {
35-
if (response == null) {
36-
return;
37-
}
38-
39-
try {
40-
final HttpEntity entity = response.getEntity();
41-
if (entity != null) {
42-
final InputStream instream = entity.getContent();
43-
instream.close();
44-
}
45-
} finally {
46-
response.close();
47-
}
33+
ResponseUtil.closeResponse(response);
4834
}
4935

5036
// tests - non-GET
5137

5238
@Test
53-
public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException {
39+
public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
5440
instance.execute(new HttpPost(SAMPLE_URL));
5541
}
5642

5743
@Test
58-
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException {
44+
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
5945
final HttpPost request = new HttpPost(SAMPLE_URL);
6046
request.setEntity(new StringEntity("in the body of the POST"));
6147
instance.execute(request);
6248
}
6349

6450
@Test
65-
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException {
51+
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
6652
final HttpPost request = new HttpPost(SAMPLE_URL);
6753
request.setEntity(new StringEntity("in the body of the POST"));
6854
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");

‎httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java

+2-14
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@
1111
import org.apache.http.impl.client.HttpClientBuilder;
1212
import org.apache.http.impl.client.HttpClients;
1313
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
14+
import org.baeldung.httpclient.ResponseUtil;
1415
import org.junit.After;
1516
import org.junit.Before;
1617
import org.junit.Test;
1718

1819
import java.io.IOException;
19-
import java.io.InputStream;
2020

2121
import static org.hamcrest.Matchers.emptyArray;
2222
import static org.hamcrest.Matchers.not;
@@ -37,19 +37,7 @@ public final void before() {
3737

3838
@After
3939
public final void after() throws IllegalStateException, IOException {
40-
if (response == null) {
41-
return;
42-
}
43-
44-
try {
45-
final HttpEntity entity = response.getEntity();
46-
if (entity != null) {
47-
final InputStream instream = entity.getContent();
48-
instream.close();
49-
}
50-
} finally {
51-
response.close();
52-
}
40+
ResponseUtil.closeResponse(response);
5341
}
5442

5543
// tests
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
package org.baeldung.httpclient.base;
22

3-
import java.io.IOException;
4-
import java.io.InputStream;
5-
6-
import org.apache.http.HttpEntity;
73
import org.apache.http.auth.AuthScope;
84
import org.apache.http.auth.UsernamePasswordCredentials;
95
import org.apache.http.client.CredentialsProvider;
@@ -12,8 +8,11 @@
128
import org.apache.http.impl.client.BasicCredentialsProvider;
139
import org.apache.http.impl.client.CloseableHttpClient;
1410
import org.apache.http.impl.client.HttpClientBuilder;
11+
import org.baeldung.httpclient.ResponseUtil;
1512
import org.junit.Test;
1613

14+
import java.io.IOException;
15+
1716
/*
1817
* NOTE : Need module spring-security-rest-basic-auth to be running
1918
*/
@@ -32,15 +31,6 @@ public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectSt
3231

3332
System.out.println(response.getStatusLine());
3433

35-
try {
36-
final HttpEntity entity = response.getEntity();
37-
if (entity != null) {
38-
// EntityUtils.consume(entity);
39-
final InputStream instream = entity.getContent();
40-
instream.close();
41-
}
42-
} finally {
43-
response.close();
44-
}
34+
ResponseUtil.closeResponse(response);
4535
}
4636
}

‎httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java

+10-10
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
package org.baeldung.httpclient.conn;
22

3-
import static org.junit.Assert.assertTrue;
4-
5-
import java.io.IOException;
6-
import java.util.concurrent.ExecutionException;
7-
import java.util.concurrent.TimeUnit;
8-
93
import org.apache.http.HeaderElement;
104
import org.apache.http.HeaderElementIterator;
115
import org.apache.http.HttpClientConnection;
@@ -36,6 +30,12 @@
3630
import org.junit.Ignore;
3731
import org.junit.Test;
3832

33+
import java.io.IOException;
34+
import java.util.concurrent.ExecutionException;
35+
import java.util.concurrent.TimeUnit;
36+
37+
import static org.junit.Assert.assertTrue;
38+
3939
public class HttpClientConnectionManagementLiveTest {
4040
private static final String SERVER1 = "http://www.petrikainulainen.net/";
4141
private static final String SERVER7 = "http://www.baeldung.com/";
@@ -129,7 +129,7 @@ public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExc
129129
@Test
130130
// @Ignore
131131
// Example 3.2. TESTER VERSION
132-
/*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
132+
/*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
133133
poolingConnManager = new PoolingHttpClientConnectionManager();
134134
final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build();
135135
final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build();
@@ -173,7 +173,7 @@ public final void whenIncreasingConnectionPool_thenNoEceptions() {
173173
@Test
174174
// @Ignore
175175
// 4.2 Tester Version
176-
/*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException {
176+
/*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException {
177177
poolingConnManager = new PoolingHttpClientConnectionManager();
178178
client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
179179
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
@@ -266,7 +266,7 @@ public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExce
266266
@Test
267267
// @Ignore
268268
// 6.2 TESTER VERSION
269-
/*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
269+
/*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
270270
poolingConnManager = new PoolingHttpClientConnectionManager();
271271
poolingConnManager.setDefaultMaxPerRoute(5);
272272
poolingConnManager.setMaxTotal(5);
@@ -333,7 +333,7 @@ public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
333333
@Test
334334
@Ignore("Very Long Running")
335335
// 8.2 TESTER VERSION
336-
/*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException {
336+
/*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException {
337337
poolingConnManager = new PoolingHttpClientConnectionManager();
338338
client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
339339
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);

‎httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread {
99
private final HttpClientConnectionManager connMgr;
1010
private volatile boolean shutdown;
1111

12-
public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
12+
IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
1313
super();
1414
this.connMgr = connMgr;
1515
}
@@ -31,7 +31,7 @@ public final void run() {
3131
}
3232
}
3333

34-
public final void shutdown() {
34+
private void shutdown() {
3535
shutdown = true;
3636
synchronized (this) {
3737
notifyAll();

‎httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java

+4-6
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread {
1818
private final HttpGet get;
1919

2020
private PoolingHttpClientConnectionManager connManager;
21-
public int leasedConn;
21+
private int leasedConn;
2222

23-
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
23+
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
2424
this.client = client;
2525
this.get = get;
2626
this.connManager = connManager;
2727
leasedConn = 0;
2828
}
2929

30-
public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
30+
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
3131
this.client = client;
3232
this.get = get;
3333
}
3434

3535
// API
3636

37-
public final int getLeasedConn() {
37+
final int getLeasedConn() {
3838
return leasedConn;
3939
}
4040

@@ -61,8 +61,6 @@ public final void run() {
6161
}
6262

6363
EntityUtils.consume(response.getEntity());
64-
} catch (final ClientProtocolException ex) {
65-
logger.error("", ex);
6664
} catch (final IOException ex) {
6765
logger.error("", ex);
6866
}

‎httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread {
1818
private final HttpGet get;
1919
private PoolingHttpClientConnectionManager connManager;
2020

21-
public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
21+
TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
2222
this.client = client;
2323
this.get = get;
2424
this.connManager = Preconditions.checkNotNull(connManager);
@@ -38,8 +38,6 @@ public final void run() {
3838

3939
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
4040
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
41-
} catch (final ClientProtocolException ex) {
42-
logger.error("", ex);
4341
} catch (final IOException ex) {
4442
logger.error("", ex);
4543
}

‎httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java

+15-17
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
package org.baeldung.httpclient.rare;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
6-
import java.io.IOException;
7-
import java.io.InputStream;
8-
import java.util.List;
9-
3+
import com.google.common.base.Preconditions;
4+
import com.google.common.collect.Lists;
105
import org.apache.commons.lang3.tuple.ImmutablePair;
116
import org.apache.commons.lang3.tuple.Pair;
127
import org.apache.http.Header;
@@ -20,8 +15,12 @@
2015
import org.junit.Before;
2116
import org.junit.Test;
2217

23-
import com.google.common.base.Preconditions;
24-
import com.google.common.collect.Lists;
18+
import java.io.IOException;
19+
import java.io.InputStream;
20+
import java.util.List;
21+
22+
import static org.hamcrest.Matchers.equalTo;
23+
import static org.junit.Assert.assertThat;
2524

2625
public class HttpClientUnshortenLiveTest {
2726

@@ -52,7 +51,7 @@ public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult(
5251

5352
// API
5453

55-
final String expand(final String urlArg) throws IOException {
54+
private String expand(final String urlArg) throws IOException {
5655
String originalUrl = urlArg;
5756
String newUrl = expandSingleLevel(originalUrl);
5857
while (!originalUrl.equals(newUrl)) {
@@ -81,7 +80,7 @@ final String expandSafe(final String urlArg) throws IOException {
8180
return newUrl;
8281
}
8382

84-
final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
83+
private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
8584
HttpHead request = null;
8685
HttpEntity httpEntity = null;
8786
InputStream entityContentStream = null;
@@ -95,15 +94,15 @@ final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOExc
9594

9695
final int statusCode = httpResponse.getStatusLine().getStatusCode();
9796
if (statusCode != 301 && statusCode != 302) {
98-
return new ImmutablePair<Integer, String>(statusCode, url);
97+
return new ImmutablePair<>(statusCode, url);
9998
}
10099
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
101100
Preconditions.checkState(headers.length == 1);
102101
final String newUrl = headers[0].getValue();
103102

104-
return new ImmutablePair<Integer, String>(statusCode, newUrl);
103+
return new ImmutablePair<>(statusCode, newUrl);
105104
} catch (final IllegalArgumentException uriEx) {
106-
return new ImmutablePair<Integer, String>(500, url);
105+
return new ImmutablePair<>(500, url);
107106
} finally {
108107
if (request != null) {
109108
request.releaseConnection();
@@ -117,7 +116,7 @@ final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOExc
117116
}
118117
}
119118

120-
final String expandSingleLevel(final String url) throws IOException {
119+
private String expandSingleLevel(final String url) throws IOException {
121120
HttpHead request = null;
122121

123122
try {
@@ -130,9 +129,8 @@ final String expandSingleLevel(final String url) throws IOException {
130129
}
131130
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
132131
Preconditions.checkState(headers.length == 1);
133-
final String newUrl = headers[0].getValue();
134132

135-
return newUrl;
133+
return headers[0].getValue();
136134
} catch (final IllegalArgumentException uriEx) {
137135
return url;
138136
} finally {

‎httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java

+16-31
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,12 @@
11
package org.baeldung.httpclient.sec;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
6-
import java.io.IOException;
7-
import java.io.InputStream;
8-
import java.nio.charset.Charset;
9-
103
import org.apache.commons.codec.binary.Base64;
11-
import org.apache.http.HttpEntity;
124
import org.apache.http.HttpHeaders;
135
import org.apache.http.HttpHost;
146
import org.apache.http.HttpStatus;
157
import org.apache.http.auth.AuthScope;
168
import org.apache.http.auth.UsernamePasswordCredentials;
179
import org.apache.http.client.AuthCache;
18-
import org.apache.http.client.ClientProtocolException;
1910
import org.apache.http.client.CredentialsProvider;
2011
import org.apache.http.client.methods.CloseableHttpResponse;
2112
import org.apache.http.client.methods.HttpGet;
@@ -26,10 +17,17 @@
2617
import org.apache.http.impl.client.CloseableHttpClient;
2718
import org.apache.http.impl.client.HttpClientBuilder;
2819
import org.apache.http.protocol.HttpContext;
20+
import org.baeldung.httpclient.ResponseUtil;
2921
import org.junit.After;
3022
import org.junit.Before;
3123
import org.junit.Test;
3224

25+
import java.io.IOException;
26+
import java.nio.charset.Charset;
27+
28+
import static org.hamcrest.Matchers.equalTo;
29+
import static org.junit.Assert.assertThat;
30+
3331
/*
3432
* NOTE : Need module spring-security-rest-basic-auth to be running
3533
*/
@@ -51,25 +49,13 @@ public final void before() {
5149

5250
@After
5351
public final void after() throws IllegalStateException, IOException {
54-
if (response == null) {
55-
return;
56-
}
57-
58-
try {
59-
final HttpEntity entity = response.getEntity();
60-
if (entity != null) {
61-
final InputStream instream = entity.getContent();
62-
instream.close();
63-
}
64-
} finally {
65-
response.close();
66-
}
52+
ResponseUtil.closeResponse(response);
6753
}
6854

6955
// tests
7056

7157
@Test
72-
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException {
58+
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
7359
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
7460

7561
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
@@ -79,7 +65,7 @@ public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_the
7965
}
8066

8167
@Test
82-
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException {
68+
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
8369
client = HttpClientBuilder.create().build();
8470
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
8571

@@ -88,7 +74,7 @@ public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWi
8874
}
8975

9076
@Test
91-
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException {
77+
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException {
9278
client = HttpClientBuilder.create().build();
9379

9480
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
@@ -100,7 +86,7 @@ public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_
10086
}
10187

10288
@Test
103-
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException {
89+
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
10490
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
10591
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
10692
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
@@ -116,14 +102,14 @@ public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_
116102

117103
// UTILS
118104

119-
private final CredentialsProvider provider() {
105+
private CredentialsProvider provider() {
120106
final CredentialsProvider provider = new BasicCredentialsProvider();
121107
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
122108
provider.setCredentials(AuthScope.ANY, credentials);
123109
return provider;
124110
}
125111

126-
private final HttpContext context() {
112+
private HttpContext context() {
127113
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
128114
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
129115
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
@@ -141,12 +127,11 @@ private final HttpContext context() {
141127
return context;
142128
}
143129

144-
private final String authorizationHeader(final String username, final String password) {
130+
private String authorizationHeader(final String username, final String password) {
145131
final String auth = username + ":" + password;
146132
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
147-
final String authHeader = "Basic " + new String(encodedAuth);
148133

149-
return authHeader;
134+
return "Basic " + new String(encodedAuth);
150135
}
151136

152137
}

‎httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java

+11-25
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
package org.baeldung.httpclient.sec;
22

3-
import static org.hamcrest.Matchers.equalTo;
4-
import static org.junit.Assert.assertThat;
5-
6-
import java.io.IOException;
7-
import java.io.InputStream;
8-
9-
import org.apache.http.HttpEntity;
10-
import org.apache.http.client.ClientProtocolException;
113
import org.apache.http.client.HttpClient;
124
import org.apache.http.client.methods.CloseableHttpResponse;
135
import org.apache.http.client.methods.HttpGet;
@@ -18,10 +10,16 @@
1810
import org.apache.http.impl.cookie.BasicClientCookie;
1911
import org.apache.http.protocol.BasicHttpContext;
2012
import org.apache.http.protocol.HttpContext;
13+
import org.baeldung.httpclient.ResponseUtil;
2114
import org.junit.After;
2215
import org.junit.Before;
2316
import org.junit.Test;
2417

18+
import java.io.IOException;
19+
20+
import static org.hamcrest.Matchers.equalTo;
21+
import static org.junit.Assert.assertThat;
22+
2523
public class HttpClientCookieLiveTest {
2624

2725
private CloseableHttpClient instance;
@@ -35,25 +33,13 @@ public final void before() {
3533

3634
@After
3735
public final void after() throws IllegalStateException, IOException {
38-
if (response == null) {
39-
return;
40-
}
41-
42-
try {
43-
final HttpEntity entity = response.getEntity();
44-
if (entity != null) {
45-
final InputStream instream = entity.getContent();
46-
instream.close();
47-
}
48-
} finally {
49-
response.close();
50-
}
36+
ResponseUtil.closeResponse(response);
5137
}
5238

5339
// tests
5440

5541
@Test
56-
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException {
42+
public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException {
5743
instance = HttpClientBuilder.create().build();
5844
final HttpGet request = new HttpGet("http://www.github.com");
5945
request.setHeader("Cookie", "JSESSIONID=1234");
@@ -64,7 +50,7 @@ public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtoc
6450
}
6551

6652
@Test
67-
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException {
53+
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException {
6854
final BasicCookieStore cookieStore = new BasicCookieStore();
6955
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
7056
cookie.setDomain(".github.com");
@@ -80,7 +66,7 @@ public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_then
8066
}
8167

8268
@Test
83-
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
69+
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException {
8470
final BasicCookieStore cookieStore = new BasicCookieStore();
8571
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
8672
cookie.setDomain(".github.com");
@@ -96,7 +82,7 @@ public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() th
9682
}
9783

9884
@Test
99-
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
85+
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException {
10086
final BasicCookieStore cookieStore = new BasicCookieStore();
10187
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
10288
cookie.setDomain(".github.com");

0 commit comments

Comments
 (0)
Please sign in to comment.