Java Magazine, July/August 2017
ORACLE COM JAVAMAGAZINE JULY AUGUST 2017 45 java 9 String join java io File separator certificatesPath ca crt String clientCertificateFileName String join java io File separator certificatesPath server crt String clientKeyFileName String join java io File separator certificatesPath server key SSLContext sslContext SecurityHelper createAndInitSSLContext caCertificateFileName clientCertificateFileName clientKeyFileName The following lines build an HttpClient instance named client by chaining many method calls after the call to the HttpClient newBuilder method that creates a new Http Client builder Some parts of the code are similar to the previous examples However in this case notice that the call to the sslContext method with the previously created SSLContext instance named sslContext as an argument makes it possible to work with HTTP 2 over TLSv12 Then the call to the version method with HttpClient Version HTTP_ 2 as an argument forces the use of HTTP 2 specifically HTTP 2 over TLSv12 because I chained the call to SSLContext too HttpClient client HttpClient newBuilder sslContext sslContext version HttpClient Version HTTP_ 2 followRedirects HttpClient Redirect ALWAYS build System out println client version URI uri new URI https your rest api url for get method 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 After the HttpClient instance is built the next line prints the result of calling the client version method JShell displays HTTP_ 2 because I forced the usage of HTTP 2 In this case you have to replace https your rest api url for get method with the URI for your REST API that allows a GET method and provides a response with HTTP 2 over TLSv12 Remember that you are using certificates so any wrong certificate will make the TLS handshake reported as an SSL handshake in the old Java names for exceptions fail With just a few addi
You must have JavaScript enabled to view digital editions.