Java 9: HTTP Client and Process API in JShell

This post continues my exploration of Java9 features from my My Top Java 9 Features blog post. Here we are experimenting with the Java 9 HTTP/2 Client and Process API in JShell.

HTTP/2 Client

The HTTP/2 Client is an incubator project in Java 9. This means the API isn’t finalized, so it has some scope for change in future versions. The most obvious changes from Java 9 to Java 10 will be moving it from the jdk.incubator.httpclient module to the “http.client” module, plus associated package name changes. It's worth keeping this in mind when using the API.

HTTP/2 doesn't work straight out the box in JShell, but it's ok, as it lets us see the Java Platform Modularity System (JPMS) in action. We simply pass the httpclient module into JShell using
–add-modules:

C:\jdk9TestGround>jshell -v --add-modules jdk.incubator.httpclient


We then import the HTTP libraries:

jshell> import jdk.incubator.http.*;


We can now call a website from JShell:

jshell> HttpClient httpClient = HttpClient.newHttpClient();
jshell> HttpRequest httpRequest = HttpRequest.newBuilder().uri(new URI("https://www.javabullets.com")).GET().build();
jshell> HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());
jshell> System.out.println(httpResponse.statusCode());
jshell> System.out.println(httpResponse.body());


The most interesting feature is the use of the Builder pattern to create the HTTP Request. This is defined in HttpRequest.Builder, which can be used to construct more complex HttpClient requests including authentication.

The syntax is similar to both the Jetty HttpClient and okhttp, which are Http/2-compliant. It is definitely much simpler than the old approach in Java.

Other useful features of this API are:

Process API

The Process API simplifies accessing process information in Java.

Consider the details of my current JShell process:

jshell> System.out.println(ProcessHandle.current().pid());
8580

jshell> System.out.println(ProcessHandle.current().info());
[user: Optional[NEW-EJ0JTJ5I9B9\javabullets], cmd: C:\Program Files\Java\jdk-9\bin\java.exe, startTime: Optional[2017-10-09T19:41:21.743Z], totalTime: Optional[PT4.625S]]

jshell> System.out.println(ProcessHandle.current().parent());
Optional[6592]


We can also access system processes and Ids:

Or info:

Now we have access to processes we can kill selective process – let's kill Notepad:

We also have the option to destroyForcibly if destroy doesn't kill the process.

The above examples show how useful and simple the Process API is for starting, killing, and monitoring processes. It frees us from relying on third-party libraries for providing process control.

 

 

 

 

Top