|
| 1 | +package com.howtoprogram.java9ex; |
| 2 | + |
| 3 | + |
| 4 | +import jdk.incubator.http.HttpClient; |
| 5 | +import jdk.incubator.http.HttpRequest; |
| 6 | +import jdk.incubator.http.HttpResponse; |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | + |
| 9 | +import java.net.Authenticator; |
| 10 | +import java.net.PasswordAuthentication; |
| 11 | +import java.net.URI; |
| 12 | +import java.util.concurrent.CompletableFuture; |
| 13 | +import java.util.concurrent.TimeUnit; |
| 14 | + |
| 15 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 16 | + |
| 17 | +public class Java9HTTP2ClientTest { |
| 18 | + |
| 19 | + public void dosth() { |
| 20 | + HttpClient defaultClient = HttpClient.newHttpClient(); |
| 21 | + |
| 22 | + HttpClient client = HttpClient.newBuilder() |
| 23 | + .version(HttpClient.Version.HTTP_2) |
| 24 | + .authenticator(new Authenticator() { |
| 25 | + @Override |
| 26 | + protected PasswordAuthentication getPasswordAuthentication() { |
| 27 | + return new PasswordAuthentication("username", "password".toCharArray()); |
| 28 | + } |
| 29 | + }) |
| 30 | + .build(); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void synchronousGetTest() throws Exception { |
| 35 | + |
| 36 | + HttpClient client = HttpClient.newHttpClient(); |
| 37 | + |
| 38 | + HttpRequest request = HttpRequest.newBuilder() |
| 39 | + .uri(new URI("https://publicobject.com/helloworld.txt")) |
| 40 | + .GET() |
| 41 | + .build(); |
| 42 | + |
| 43 | + HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); |
| 44 | + assertEquals(200, response.statusCode()); |
| 45 | + |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void getWithQueryParametersTest() throws Exception { |
| 50 | + |
| 51 | + HttpClient client = HttpClient.newHttpClient(); |
| 52 | + |
| 53 | + HttpRequest request = HttpRequest.newBuilder() |
| 54 | + .uri(new URI("https://publicobject.com/helloworld.txt")) |
| 55 | + .GET() |
| 56 | + .build(); |
| 57 | + |
| 58 | + HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); |
| 59 | + assertEquals(200, response.statusCode()); |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | + @Test |
| 64 | + public void asynchronousGetTest() throws Exception { |
| 65 | + |
| 66 | + HttpClient client = HttpClient.newHttpClient(); |
| 67 | + |
| 68 | + HttpRequest request = HttpRequest.newBuilder() |
| 69 | + .uri(new URI("https://publicobject.com/helloworld.txt")) |
| 70 | + .GET() |
| 71 | + .build(); |
| 72 | + CompletableFuture<HttpResponse<String>> response = client.sendAsync(request, |
| 73 | + HttpResponse.BodyHandler.asString()); |
| 74 | + |
| 75 | + HttpResponse<String> actualResponse = response.get(1000, TimeUnit.MINUTES); |
| 76 | + assertEquals(200, actualResponse.statusCode()); |
| 77 | + |
| 78 | + } |
| 79 | +} |
0 commit comments