Java Magazine, July/August 2017
ORACLE COM JAVAMAGAZINE JULY AUGUST 2017 42 java 9 Working with Asynchronous Execution Before demonstrating the usage of the client to work with HTTP 2 and TLS Ill work with the asynchronous API JShell includes many import statements by default However if you dont work with JShell you need to add the following additional import statement for the next sample code to work import java util concurrent CompletableFuture In the previous lines that worked with synchronous execution I called the client send method Now I will write similar code to build the HttpRequest and this time I will call the client sendAsync method that returns a CompletableFuture HttpResponse String This way you can take advantage of the support of dependent functions and actions that a java util concurrent CompletableFuture T triggers upon its completion and write code that uses the HttpResponse String If youre not familiar with completable futures have a look at the explanation of them in Andrés Almirays article on JDeferred in the May June 2017 issue of Java Magazine Ed In the following code I call response whenComplete to run code that prints the results of the statusCode and body length methods that provide the HTTP status code returned by the response and the length of the body retrieved as a String if no exception was thrown Because the asynchronous task generated under the hood can throw an exception I specify HttpResponse String response and Throwable exception when I declare the lambda expression that will be executed when the asynchronous task is completed In the lambda expression body I work with the response after making sure that the exception argument is null HttpClient client HttpClient newBuilder followRedirects HttpClient Redirect ALWAYS build URI uri new URI http www oracle com HttpRequest request HttpRequest newBuilder uri uri GET build CompletableFuture HttpResponse String response client sendAsync request HttpResponse BodyHandler asString response whenComplete HttpResponse String response Throwable exception if exception null System out println String format Status code d response statusCode System out println String format Body length d response body length else System out println String format Something went wrong s exception getMessage With just these few lines of code in JShell I was able to use the new HTTP client with a very basic configuration and its asynchronous API Working with HTTP 2 over TLS The HTTP client uses standard Java TLS mechanisms to enable work with HTTP 2 over TLS h2 To do this programmatically it is necessary to create and initialize a javax net ssl SSLContext instance and pass it as an argument to the sslContext method chained to the HttpClient builder The
You must have JavaScript enabled to view digital editions.