Skip to content

Commit ffd66fa

Browse files
authored
Refactor HttpClient (eugenp#2272)
1 parent 14456eb commit ffd66fa

21 files changed

Lines changed: 230 additions & 350 deletions

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

Lines changed: 2 additions & 7 deletions
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

Lines changed: 4 additions & 19 deletions
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

Lines changed: 39 additions & 48 deletions
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

Lines changed: 17 additions & 23 deletions
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

0 commit comments

Comments
 (0)