Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Anthony Bruno
Anthony Bruno

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()
Enter fullscreen modeExit fullscreen mode

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())
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
pojntfx profile image
Felicitas Pojtinger
  • Pronouns
    she/her
  • Joined

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);
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
aussieguy profile image
Anthony Bruno
Australian software engineer. Probably drinking coffee right now.
  • Location
    Australia
  • 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.

CollapseExpand
 
cscbnguyen43 profile image
Binh Thanh Nguyen
  • Joined

Thanks, nice tips

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Australian software engineer. Probably drinking coffee right now.
  • Location
    Australia
  • Joined

More fromAnthony Bruno

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp