Skip to content

Commit bdae4fe

Browse files
abialasmaibin
authored andcommitted
BAEL-21 new Java9 HTTP API overview (eugenp#3536)
* BAEL-1412 add java 8 spring data features * BAEL-21 new HTTP API overview
1 parent b0191da commit bdae4fe

3 files changed

Lines changed: 441 additions & 0 deletions

File tree

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
package com.baeldung.java9.httpclient;
2+
3+
import jdk.incubator.http.HttpClient;
4+
import jdk.incubator.http.HttpRequest;
5+
import jdk.incubator.http.HttpResponse;
6+
import org.junit.Test;
7+
8+
import java.io.IOException;
9+
import java.net.*;
10+
import java.util.Arrays;
11+
import java.util.List;
12+
import java.util.concurrent.CompletableFuture;
13+
import java.util.concurrent.ExecutionException;
14+
import java.util.concurrent.Executors;
15+
import java.util.stream.Collectors;
16+
17+
import static org.hamcrest.CoreMatchers.containsString;
18+
import static org.hamcrest.CoreMatchers.equalTo;
19+
import static org.hamcrest.collection.IsEmptyCollection.empty;
20+
import static org.hamcrest.core.IsNot.not;
21+
import static org.junit.Assert.assertThat;
22+
23+
/**
24+
* Created by adam.
25+
*/
26+
public class HttpClientTest {
27+
28+
@Test
29+
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
30+
HttpRequest request = HttpRequest.newBuilder()
31+
.uri(new URI("https://postman-echo.com/post"))
32+
.headers("Content-Type", "text/plain;charset=UTF-8")
33+
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
34+
.build();
35+
36+
HttpResponse<String> response = HttpClient.newBuilder()
37+
.proxy(ProxySelector.getDefault())
38+
.build()
39+
.send(request, HttpResponse.BodyHandler.asString());
40+
41+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
42+
assertThat(response.body(), containsString("Sample body"));
43+
}
44+
45+
@Test
46+
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
47+
HttpRequest request = HttpRequest.newBuilder()
48+
.uri(new URI("http://stackoverflow.com"))
49+
.version(HttpClient.Version.HTTP_1_1)
50+
.GET()
51+
.build();
52+
HttpResponse<String> response = HttpClient.newBuilder()
53+
.build()
54+
.send(request, HttpResponse.BodyHandler.asString());
55+
56+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
57+
assertThat(response.body(), containsString("https://stackoverflow.com/"));
58+
}
59+
60+
@Test
61+
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
62+
HttpRequest request = HttpRequest.newBuilder()
63+
.uri(new URI("http://stackoverflow.com"))
64+
.version(HttpClient.Version.HTTP_1_1)
65+
.GET()
66+
.build();
67+
HttpResponse<String> response = HttpClient.newBuilder()
68+
.followRedirects(HttpClient.Redirect.ALWAYS)
69+
.build()
70+
.send(request, HttpResponse.BodyHandler.asString());
71+
72+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
73+
assertThat(response.finalRequest()
74+
.uri()
75+
.toString(), equalTo("https://stackoverflow.com/"));
76+
}
77+
78+
@Test
79+
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
80+
HttpRequest request = HttpRequest.newBuilder()
81+
.uri(new URI("https://postman-echo.com/basic-auth"))
82+
.GET()
83+
.build();
84+
HttpResponse<String> response = HttpClient.newBuilder()
85+
.authenticator(new Authenticator() {
86+
@Override
87+
protected PasswordAuthentication getPasswordAuthentication() {
88+
return new PasswordAuthentication("postman", "password".toCharArray());
89+
}
90+
})
91+
.build()
92+
.send(request, HttpResponse.BodyHandler.asString());
93+
94+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
95+
}
96+
97+
@Test
98+
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
99+
HttpRequest request = HttpRequest.newBuilder()
100+
.uri(new URI("https://postman-echo.com/post"))
101+
.headers("Content-Type", "text/plain;charset=UTF-8")
102+
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
103+
.build();
104+
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
105+
.build()
106+
.sendAsync(request, HttpResponse.BodyHandler.asString());
107+
108+
assertThat(response.get()
109+
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
110+
}
111+
112+
@Test
113+
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
114+
HttpRequest request = HttpRequest.newBuilder()
115+
.uri(new URI("https://postman-echo.com/get"))
116+
.GET()
117+
.build();
118+
119+
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
120+
.executor(Executors.newFixedThreadPool(2))
121+
.build()
122+
.sendAsync(request, HttpResponse.BodyHandler.asString());
123+
124+
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
125+
.executor(Executors.newFixedThreadPool(2))
126+
.build()
127+
.sendAsync(request, HttpResponse.BodyHandler.asString());
128+
129+
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
130+
.executor(Executors.newFixedThreadPool(2))
131+
.build()
132+
.sendAsync(request, HttpResponse.BodyHandler.asString());
133+
134+
CompletableFuture.allOf(response1, response2, response3)
135+
.join();
136+
137+
assertThat(response1.get()
138+
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
139+
assertThat(response2.get()
140+
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
141+
assertThat(response3.get()
142+
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
143+
}
144+
145+
@Test
146+
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
147+
HttpRequest request = HttpRequest.newBuilder()
148+
.uri(new URI("https://postman-echo.com/get"))
149+
.GET()
150+
.build();
151+
152+
HttpClient httpClient = HttpClient.newBuilder()
153+
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
154+
.build();
155+
156+
httpClient.send(request, HttpResponse.BodyHandler.asString());
157+
158+
assertThat(httpClient.cookieManager()
159+
.get()
160+
.getCookieStore()
161+
.getCookies(), empty());
162+
}
163+
164+
@Test
165+
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
166+
HttpRequest request = HttpRequest.newBuilder()
167+
.uri(new URI("https://postman-echo.com/get"))
168+
.GET()
169+
.build();
170+
171+
HttpClient httpClient = HttpClient.newBuilder()
172+
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
173+
.build();
174+
175+
httpClient.send(request, HttpResponse.BodyHandler.asString());
176+
177+
assertThat(httpClient.cookieManager()
178+
.get()
179+
.getCookieStore()
180+
.getCookies(), not(empty()));
181+
}
182+
183+
@Test
184+
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
185+
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
186+
187+
HttpClient client = HttpClient.newHttpClient();
188+
189+
List<CompletableFuture<String>> futures = targets.stream()
190+
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
191+
.GET()
192+
.build(), HttpResponse.BodyHandler.asString())
193+
.thenApply(response -> response.body()))
194+
.collect(Collectors.toList());
195+
196+
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
197+
.join();
198+
199+
if (futures.get(0)
200+
.get()
201+
.contains("foo1")) {
202+
assertThat(futures.get(0)
203+
.get(), containsString("bar1"));
204+
assertThat(futures.get(1)
205+
.get(), containsString("bar2"));
206+
} else {
207+
assertThat(futures.get(1)
208+
.get(), containsString("bar2"));
209+
assertThat(futures.get(1)
210+
.get(), containsString("bar1"));
211+
}
212+
213+
}
214+
215+
}
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
package com.baeldung.java9.httpclient;
2+
3+
import jdk.incubator.http.HttpClient;
4+
import jdk.incubator.http.HttpRequest;
5+
import jdk.incubator.http.HttpResponse;
6+
import org.junit.Test;
7+
8+
import java.io.ByteArrayInputStream;
9+
import java.io.IOException;
10+
import java.net.HttpURLConnection;
11+
import java.net.URI;
12+
import java.net.URISyntaxException;
13+
import java.nio.file.Paths;
14+
import java.security.NoSuchAlgorithmException;
15+
import java.time.Duration;
16+
17+
import static java.time.temporal.ChronoUnit.SECONDS;
18+
import static org.hamcrest.CoreMatchers.containsString;
19+
import static org.hamcrest.CoreMatchers.equalTo;
20+
import static org.junit.Assert.assertThat;
21+
22+
/**
23+
* Created by adam.
24+
*/
25+
public class HttpRequestTest {
26+
27+
@Test
28+
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
29+
HttpRequest request = HttpRequest.newBuilder()
30+
.uri(new URI("https://postman-echo.com/get"))
31+
.GET()
32+
.build();
33+
34+
HttpResponse<String> response = HttpClient.newHttpClient()
35+
.send(request, HttpResponse.BodyHandler.asString());
36+
37+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
38+
}
39+
40+
@Test
41+
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
42+
HttpRequest request = HttpRequest.newBuilder()
43+
.uri(new URI("https://stackoverflow.com"))
44+
.version(HttpClient.Version.HTTP_2)
45+
.GET()
46+
.build();
47+
HttpResponse<String> response = HttpClient.newHttpClient()
48+
.send(request, HttpResponse.BodyHandler.asString());
49+
50+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
51+
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
52+
}
53+
54+
@Test
55+
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
56+
HttpRequest request = HttpRequest.newBuilder()
57+
.uri(new URI("https://postman-echo.com/get"))
58+
.version(HttpClient.Version.HTTP_2)
59+
.GET()
60+
.build();
61+
62+
HttpResponse<String> response = HttpClient.newHttpClient()
63+
.send(request, HttpResponse.BodyHandler.asString());
64+
65+
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
66+
}
67+
68+
@Test
69+
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
70+
HttpRequest request = HttpRequest.newBuilder()
71+
.uri(new URI("https://postman-echo.com/get"))
72+
.headers("key1", "value1", "key2", "value2")
73+
.GET()
74+
.build();
75+
76+
HttpResponse<String> response = HttpClient.newHttpClient()
77+
.send(request, HttpResponse.BodyHandler.asString());
78+
79+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
80+
}
81+
82+
@Test
83+
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
84+
HttpRequest request = HttpRequest.newBuilder()
85+
.uri(new URI("https://postman-echo.com/get"))
86+
.timeout(Duration.of(10, SECONDS))
87+
.GET()
88+
.build();
89+
90+
HttpResponse<String> response = HttpClient.newHttpClient()
91+
.send(request, HttpResponse.BodyHandler.asString());
92+
93+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
94+
}
95+
96+
@Test
97+
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
98+
HttpRequest request = HttpRequest.newBuilder()
99+
.uri(new URI("https://postman-echo.com/post"))
100+
.POST(HttpRequest.noBody())
101+
.build();
102+
103+
HttpResponse<String> response = HttpClient.newHttpClient()
104+
.send(request, HttpResponse.BodyHandler.asString());
105+
106+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
107+
}
108+
109+
@Test
110+
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
111+
HttpRequest request = HttpRequest.newBuilder()
112+
.uri(new URI("https://postman-echo.com/post"))
113+
.headers("Content-Type", "text/plain;charset=UTF-8")
114+
.POST(HttpRequest.BodyProcessor.fromString("Sample request body"))
115+
.build();
116+
117+
HttpResponse<String> response = HttpClient.newHttpClient()
118+
.send(request, HttpResponse.BodyHandler.asString());
119+
120+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
121+
assertThat(response.body(), containsString("Sample request body"));
122+
}
123+
124+
@Test
125+
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
126+
byte[] sampleData = "Sample request body".getBytes();
127+
HttpRequest request = HttpRequest.newBuilder()
128+
.uri(new URI("https://postman-echo.com/post"))
129+
.headers("Content-Type", "text/plain;charset=UTF-8")
130+
.POST(HttpRequest.BodyProcessor.fromInputStream(() -> new ByteArrayInputStream(sampleData)))
131+
.build();
132+
133+
HttpResponse<String> response = HttpClient.newHttpClient()
134+
.send(request, HttpResponse.BodyHandler.asString());
135+
136+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
137+
assertThat(response.body(), containsString("Sample request body"));
138+
}
139+
140+
@Test
141+
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
142+
byte[] sampleData = "Sample request body".getBytes();
143+
HttpRequest request = HttpRequest.newBuilder()
144+
.uri(new URI("https://postman-echo.com/post"))
145+
.headers("Content-Type", "text/plain;charset=UTF-8")
146+
.POST(HttpRequest.BodyProcessor.fromByteArray(sampleData))
147+
.build();
148+
149+
HttpResponse<String> response = HttpClient.newHttpClient()
150+
.send(request, HttpResponse.BodyHandler.asString());
151+
152+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
153+
assertThat(response.body(), containsString("Sample request body"));
154+
}
155+
156+
@Test
157+
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
158+
HttpRequest request = HttpRequest.newBuilder()
159+
.uri(new URI("https://postman-echo.com/post"))
160+
.headers("Content-Type", "text/plain;charset=UTF-8")
161+
.POST(HttpRequest.BodyProcessor.fromFile(Paths.get("src/test/resources/sample.txt")))
162+
.build();
163+
164+
HttpResponse<String> response = HttpClient.newHttpClient()
165+
.send(request, HttpResponse.BodyHandler.asString());
166+
167+
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
168+
assertThat(response.body(), containsString("Sample file content"));
169+
}
170+
171+
}

0 commit comments

Comments
 (0)