Week 38 — How can one make an HTTP request in a Java application?
Question of the Week #38
How can one make an HTTP request in a Java application?
7 Replies
You can make an HTTP request in a Java application using the built-in java.net package or by using popular third-party libraries like Apache HttpClient or OkHttp.
Submission from maziogra
Http Requests in Java (The OG Way)
The simplest way to make an http request in Java is by using the
URLConnection
abstract class of the java.net
package. The following example shows a GET
request to some api on the localhost server:
Although we didn't directly interact with the URLConnection
class, the openStream()
method is short for
where openConnection()
returns the URLConnection
instance. This stream represents the connection between the client and the web server where we are implicitly sending a GET
request and getting a response back. Next, A BufferedReader
is created to easily read data coming from the that response. Then we loop through each line sent by the sever with the readLine()
, printing it to the console. Lastly we need to handle an IOException that could be thrown by the stream so we catch the exception in the catch clause of our try-with-resource clause.
Although simple, this example is restricted only to an http GET
request. You can use a
subclass of URLConntion
, HttpURLConnection
for http specific configuration such as changing
the request method or setting a request header. Here is an example using a POST
request to
update the api by adding a course, using the more specific httpURLConnection
class.
Since, getConnection() returns an instance of HttpURLConnection
as of type URLConnection
we need to cast the value in order to make a POST
request. We first set the request method to "POST" using the setRequestMethod()
method. We then set the "Content-Type" to "application/json" as that's what your REST api endpoint consumes. We also set the DoOutput
to true signaling that we want to write to the output stream. Next, we create a BufferedWriter
in order to easily send the Json data as a String over to the server. Lastly, we check the status of our request to see if it equals an HTTP_OK
meaning that our request was successful.Http Request as of Java 11
As of Java 11 a new and improved Http Client was created to replace
HttpURLConnection
. It uses the Builder Pattern to provide a higher level of abstraction with support for asynchronous requests, contrary to pre-Java 11. Here is a quick overview of the different components the new API offers:
HttpClient
- Used to send requests to a server using the HttpRequest. The client can choose how to send the request (asynchronous or synchronous).
HttpRequest
- Uses Builder methods to create a Request that an HttpClient instance will send.
Here is a quick example using the course api from the previous examples:
⭐ Submission from karter907
Java provides multiple ways of executing HTTP requests and obtaining responses. One of them is the class
HTTPClient
which has been introduced in Java 11.
A HttpClient
with the default configuration can be instantiated using the factory method HttpClient.newHttpClient();
. Alternatively, it is possible to create a configure the HttpClient
using a builder:
The same HttpClient can be used for multiple requests.
For sending HTTP requests, one needs an instance of HttpRequest which can be instantiated using a builder:
HttpRequest
s can be sent using the HttpClient
either synchronously using the method send or asynchronously with the method sendAsync
. send
returns a HttpResponse
which can be used for analyzing the response while sendAsync
returns a CompletableFuture
of a HttpResponse
which can be used for registering callbacks.
Both send
and sendAsync
require a BodyHandler
which is used for converting the response body to an object (e.g. a String
, InputStream
or byte[]
or even custom logic (like parsing JSON)).
A different way of sending HTTP requests from Java which has been available in the standard libraries for longer is using HttpURLConnection
.
With this, it's possible to create a URL
-object representing the page to request and then sending a request to that URL as well as reading the response.
In case of a GET request that just requires the result body, it's possible to get an InputStream
for reading the response using URl#openStream
:
It is also possible to get a
Connection
object from the URL
using URL#openConnection
. In the case of http://
or https://
-URLs, this wll be a HttpURLConnection
. This allows more detailed access to it.
⭐ Submission from dan1st
There are several ways to do that, but the most modern would be using the HttpClient introduced not so long ago. It provides a clean api one can easily work with.
Asynchronous requests are also possible:
Another rather old way to do what we did above is to use the URL and HttpURLConnection mechanism:
Although the URL and HttpURLConnection apis are very old, they still work. I wouldn't use them over the HttpClient api if available, since the HttpClient api is easier to use and supports all of the functionality of HttpURLConnection, along with some features exclusive to HttpClient.
There are third party http client APIs, but HttpClient will probably suffice just fine. If in doubt, just roll your own with Socket ;):
⭐ Submission from 0x150