Posted on • Edited on • Originally published atanthonybruno.dev
A quick look at Java 11's HttpClient
This article was originally posted onmy blog
Java 11 was released in September 2018 and is the first Long-Term-Support version after Java 8. One of its features isHttpClient, a new way to make HTTP requests. This post will give a quick overview of HttpClient, and how it's a much-needed replacement forURLConnection!
The task
I've created a page on my websitehttp://anthonybruno.dev/last-update that simply has a Unix timestamp of the last time the site was built.
The task is simple, create some code that requests this page and returns the
timestamp!
Using URLConnection
Below is the code that usesURLConnection
.
// 1. Create URL objectURLupdateUrl=newURL("http://anthonybruno.com.au/last-update");// 2. We use openConnection() on the url to get a HttpURLConnection,// that we have to cast(?!). Also, this doesn't actually make a// network request(?!?!?)HttpURLConnectionconnection=(HttpURLConnection)updateUrl.openConnection();// 3. We can then set things like set request methods, headers.connection.setRequestMethod("GET");// 4. Then we actually connect! Note: connect doesn't return anything, it// mutates the connection object!connection.connect();intstatusCode=connection.getResponseCode();if(statusCode!=200){thrownewRuntimeException("Got non 200 response code! "+statusCode);}// 5. Content is returned in an InputStream (Don't forget to close it!)InputStreamcontent=connection.getInputStream()Instanttimestamp=processIntoInstant(content)// 6. Remember to disconnect! Note: HttpURLConnnection is not autoclosable!connection.disconnect()
After creating theURL
object, things quickly go awry. It's extremely
counter-intuitive to use a method calledopenConnection()
, that doesn't actually open a connection! Having to cast the returnedURLConnection
object toHttpURLConnection
to access methods likesetRequestMethod
anddisconnect
is plain silly. Finally, callingconnect()
(which actually makes a network request!) doesn't return anything, instead, you have to get response information from theconnection
object itself.
Using HttpClient
Below is the code that usesHttpClient
. You'll see a big difference.
// 1. Create HttpClient objectHttpClienthttpClient=HttpClient.newHttpClient();// 2. Create URI objectURIuri=URI.create(updateUrl);// 3. Build a requestHttpRequestrequest=HttpRequest.newBuilder(uri).GET().build();// 4. Send the request and get a HttpResponse object back!// Note: HttpResponse.BodyHandlers.ofString() just parses the response body// as a StringHttpResponse<String>response=httpClient.send(request,HttpResponse.BodyHandlers.ofString());intstatusCode=response.statusCode();if(statusCode!=200){thrownewRuntimeException("Got non 200 response code! "+statusCode);}Instanttimestamp=processIntoInstant(response.body())
Now, isn't that much nicer than theURlConnection
code we saw before? We first set up aHttpClient
object, which will send our requests. We then instantiate aHttpRequest
object, which holds the request method, headers, etc. We send theHttpRequest
, using the previously createdHttpClient
, giving us a niceHttpResponse
object back.
The second parameter inhttpClient.send
is aBodyHandler
, which is
responsible for parsing the response body into the format you want. Java provides a bunch of default ones inBodyHandlers
, that covers common use cases like parsing toString
,File
andInputStream
. Of course, it's possible to create your own, which deserves an article by itself.
The idea of creating a client, creating requests and receiving responses is quite a bit more intuitive than usingURlConnection
!HttpClient
also supports asynchronous requests, HTTP/2 and websockets. It's an enticing reason to migrate from 8 to 11!
Code used in this article can be foundhere
Top comments(3)

Nice article!
I have to say though; the more I learn about Java the more I love JS:
constres=awaitfetch("http://anthonybruno.com.au/last-update");consttext=res.text();console.log(text);

- LocationAustralia
- Joined
Thanks for reading :)
Unfourtantly, Java does have a verbosity problem, especially compared to a dynamic language like Javascript!fetch
does have a great API. It's much nicer than the olderXMLHttpRequest
.
For further actions, you may consider blocking this person and/orreporting abuse