This post will discuss how to send HTTP POST request in Java.

1. Using java.net.URLConnection

The URLConnection class offers several methods to communicate with the URL over the network. We can use this class for reading and writing directly to the resource referenced by the URL.

The following program retrieves an URLConnection object by invoking the openConnection() method on an URL and gets an input stream by calling getInputStream(). Then the program creates a BufferedReader on the input stream and reads from it.

To send HTTP POST request, don’t forget to set URLConnection.setDoOutput() method to true and also write the POST parameters to the output stream of the connection.

Download Code

2. Using java.net.HttpUrlConnection

Since we’re working with HTTP, it is preferable to use HttpURLConnection over superclass URLConnection, which comes with support for HTTP-specific features. To get a HttpURLConnection object, simply cast URLConnection instance to a HttpURLConnection.

Then to send HTTP POST request, pass POST string literal to the setRequestMethod() method of HttpURLConnection object. This is no doubt a better alternative than relying on setDoOutput() method of URLConnection class.

This is demonstrated below:

Download Code

3. Using Apache HttpClient API

If your project is open to external libraries, consider using Apache HttpClient API for executing HTTP methods. HttpClient internally handles one or more HTTP request / HTTP response exchanges needed to execute an HTTP method successfully. The user is expected to provide a request object to execute, and HttpClient is expected to transmit the request to the target server, return a corresponding response object, or throw an exception if the execution was unsuccessful.

Here’s a simple example that demonstrates how we can use HttpClient APIs to send HTTP POST request. Please refer to official HttpClient Examples to get an in-depth understanding of all features offered by this module.

Download Code

 
It is worth noting that, like Apache HttpClient, several other Java libraries are available that facilitate easier HTTP requests from Java code. The coverage of any other third-party library is beyond the scope of this article.

That’s all about making an HTTP POST request in Java.