

Java 9 comes with new HTTP client api that implements http/2 and websocket and it can replace old HttpURLConnection api.
It will be delivered as an incubator module.
There are mainly three handy classes HttpClinet , HttpRequest , HttpResponse
Table of Contents
HttpRequest:
Represents one HTTP request which can be sent to a server. HttpRequest
s are built from HttpRequest
builder
s. HttpRequest
builders are obtained from a HttpClient
by calling HttpClient.request
, or by calling HttpRequest.create
which returns a builder on the default client.
HttpResponse:
Represents a response to a HttpRequest
. A HttpResponse
is available when the response status code and headers have been received, but before the response body is received.
Note:
Below examples requires jdk.incubator.httpclient,It should be in our module-info.java.Refer Java 9 module example for more details on modularity.
Example 1:
Using new http client api we can build HttpRequest ,send using HttpClinet and define response bodyhandler,here we have use asString as a response body handler.We can also get information regarding sslParameters like maximum packet size ,cipher suits , client authentication needed or not , etc…
public void getHttpResponseAsString(){ try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javadeveloperzone.com/java-basic/java-9-features/java-9-module-example/")) .GET() .build(); //String body handler HttpResponse<String> strResponse = client.send(request, HttpResponse.BodyHandler.asString()); System.out.println(strResponse.statusCode()); SSLParameters sslParameters = strResponse.sslParameters(); System.out.println("Maximum packet size : "+sslParameters.getMaximumPacketSize()); //System.out.println(response.body()); } catch (URISyntaxException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Example 2: (Save HttpResponse in local file)
We can save response in our local file system using HttpResponse.BodyHandler.asFile() method.
public void saveHttpResponseAsFile(){ try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javadeveloperzone.com/java-basic/java-9-features/java-9-module-example/")) .GET() .build(); //String body handler HttpResponse<String> strResponse = client.send(request, HttpResponse.BodyHandler.asString()); //Path tempFile = Files.createFile("test", ".html"); Path tempFile = Paths.get("G:\\study\\Blogs\\Applications\\Sample.html"); HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandler.asFile(tempFile)); System.out.println(response.statusCode()); //System.out.println(response.body()); } catch (URISyntaxException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Example 3 : (Asynchronous HTTP Request)
sendAsSync method of HttpClient class is used to send an asynchronous request to servers. We can kill any request if it takes more than a specified time duration.
public void sendAsynchronousRequest(){ try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javadeveloperzone.com/java-basic/java-9-features/java-9-module-example/")) .GET() .build(); //String body handler CompletableFuture<HttpResponse<String>> strResponse = client.sendAsync(request, HttpResponse.BodyHandler.asString()); Thread.sleep(200); if(strResponse.isDone()){ System.out.println(strResponse.get().statusCode()); }else{ System.out.println("Request take more than 200 millisecons..."); strResponse.cancel(true); if(strResponse.isCancelled()){ System.out.println("request cancelled !!!"); } } //System.out.println(response.body()); } catch (URISyntaxException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
Output:
WARNING: Using incubator modules: jdk.incubator.httpclient Request take more than 200 milliseconds... request cancelled !!!
Example 4 : (Set Basic Authentication)
We can set username and password using an authenticator.
public void setBasicAuth(){ try { HttpClient client = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password".toCharArray()); } }) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://javadeveloperzone.com/java-basic/java-9-features/java-9-module-example/")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString()); System.out.println(response.statusCode()); System.out.println(response.body()); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } }
References:
Source Code:
Click here to Download Source Code
You can also download the source code of Java 9 New Http Client API Example from our git repository.