1. Overview
This tutorial is going to cover Java 9 HTTP/2 Client API. We’ll get through how to create a HttpClient object, make HTTP requests and handle HTTP Responses.
Notice that the HTTP/2 Client API is an incubator module named jdk.incubator.httpclient which has been introduced in Java 9. And as mentioned in the link, because the jdk.incubator.httpclient API and its implementation are not part of Java SE 9, those will not be resolved by default at compile or run time.
2. Create A Java 9 HTTP/2 Client Object
There are two ways for us to create a Java 9 HTTP/2 client object:
2.1. Using the HttpClient class
1 |
HttpClient httpClient = HttpClient.newHttpClient(); |
2.2. Using the HttpClient.Builder class
1 2 3 4 5 6 7 8 9 |
HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password".toCharArray()); } }) .build(); |
3. GET Request Examples
3.1. Make A Synchronous GET Request
To make a synchronous GET request we will need to provide the Request Builder the target URI, set the request method of this builder to GET and call the send() method of the client to send the request. Notice that the send() method will block if it’s necessary to get the response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Test public void synchronousGetTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://publicobject.com/helloworld.txt")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); } |
3.2. Make An Asynchronous GET
Making an asynchronous GET request is similar to making a synchronous GET request except that we call the sendAsync() method instead of the send() method of the client to send the given request asynchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void asynchronousGetTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://publicobject.com/helloworld.txt")) .GET() .build(); CompletableFuture<HttpResponse<String>> response = client.sendAsync(request, HttpResponse.BodyHandler.asString()); HttpResponse<String> actualResponse = response.get(1000, TimeUnit.MINUTES); assertEquals(200, actualResponse.statusCode()); } |
4. POST Request Examples
4.1. Make A Post Request
To make a POST request using Java 9 HTTP/2 client API, we will need to set the request method of the HttpRequest builder to POST and set its request body processor to the given value, then build and return a HttpRequest, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void basicPostTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://httpbin.org/post")).POST( HttpRequest.BodyProcessor.fromString("param1=foo,param2=bar")) .version(HttpClient.Version.HTTP_1_1) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); System.out.println(response.body()); } |
4.2. Post A Byte Array
To post a byte array, we simply need to provide the HttpRequest builder a request body processor whose body is the given byte array, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void postByteArrayTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); byte[] body = "Java 9 HTTP 2 Client API Example".getBytes(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://httpbin.org/post")).POST( HttpRequest.BodyProcessor.fromByteArray(body)) .version(HttpClient.Version.HTTP_1_1) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); System.out.println(response.body()); } |
4.3. Upload A File Using POST Request
To upload a file using POST request, we will need to form up a request body processor that takes data from the contents of the file by calling the fromFile() static method of the BodyProcessor class, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Test public void uploadFileTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); File file = new File("src/test/resources/LoremIpsum.txt"); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://httpbin.org/post")).POST( HttpRequest.BodyProcessor.fromFile(file.toPath())) .version(HttpClient.Version.HTTP_1_1) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); System.out.println(response.body()); } |
5. Basic Authentication
To make a request to a server which requires authentication using Java 9 HTTP/2 client API, we can supply the HttpClient with an Authenticator interface, for example, below is how we do basic authentication with the http://httpbin.org/ service:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Test public void basicAuthGetTest() throws Exception { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("user", "passwd".toCharArray()); } }) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://httpbin.org/basic-auth/user/passwd")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); } |
6. Set Headers For A Request
To set headers for a Request we can use a simple header(), or setHeader() call:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@Test public void setHeaderTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://httpbin.org/headers")) .version(HttpClient.Version.HTTP_1_1) .GET() .header("page","1") .header("sort", "asc") .setHeader("limit", "20") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); System.out.println(response.body()); } |
7. Set A Timeout For A Request
To set a timeout for a request, we can supply the timeout() method of the request builder a timeout. If the response is not received within the specified timeout then a HttpTimeoutException will be thrown, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Test public void setTimeoutTest() throws Exception { HttpClient client = HttpClient.newHttpClient(); int delay = 10; //seconds HttpRequest request = HttpRequest.newBuilder() .uri(new URI("http://httpbin.org/delay/" + delay)) .version(HttpClient.Version.HTTP_1_1) .GET() .timeout(Duration.ofSeconds(delay - 5)) .build(); assertThrows(HttpTimeoutException.class, () -> { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); }); } |
If we don’t set a timeout for a request, it is the same as setting an infinite duration.
8. Set A Proxy For A HttpClient
To set a proxy for a HttpClient, we simply need to supply it a ProxySelector which will select the proxy server to use, if any, when the client connects to any network resource, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Test public void setProxyTest() throws Exception { HttpClient client = HttpClient.newBuilder() .proxy(ProxySelector.getDefault()) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://publicobject.com/helloworld.txt")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); assertEquals(200, response.statusCode()); } |
In the above example, we use the ProxySelector.getDefault() method to get the system-wide proxy selector.
9. Conclusions
The tutorial has shown us how to use Java 9 HTTP/2 client API with different examples. We got through how to create Java 9 HTTP/2 client objects, make GET requests, make POST requests, upload a file and configure other values for the HttpClient, HttpRequest as well.
The source code presented in the tutorial is available on my Github project. It’s a Maven based project, so it’s easy to be imported into IDE such as Eclipse, IntelliJ, etc.
Below are other related articles for your references:
Install Oracle Java 9 on CentOS, RHEL 7
Install Oracle Java 9 on Ubuntu 16.04 LTS (Xenial Xerus)
Set Up Eclipse, IntelliJ And NetBeans For Java 9
Java 9 Example With Maven And JUnit 5
Create Immutable Lists In Java 9 By Static Factory Methods
Private Interface Methods In Java 9
Using The InputStream.transferTo() To Copy Streams In Java 9
Java 9 – New Methods Of The Optional Class
Java 9 – Effectively Final Variables In try-with-resources