Social Media

Category Archives for Java

Experimenting with Java9 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 Java9 HTTP/2 Client and Process API in JShell

HTTP/2 Client

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

The HTTP/2 doesnt work straight out the box in jshell, but its 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 –

We then import the http libraries –

We can now call a website from jshell –

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 –

  • Asynchronous Requests – This is more useful than the above example as it is non-blocking. This is done through the HttpRequest.sendAsync method
  • WebSockets – This is created through the WebSocket class which has its own WebSocket.Builder. I’m going to cover this in another post as its clearer than on jshell

Process API

The process API simplifies accessing Process information in Java.

Consider the details of my current Jshell process –

We can also access System processes and Id’s –

Or Info –

Now we have access to processes we can kill selective process – lets kill notepad –

We also have the option to destroyForcibly if destroy doesnt kill the process.

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