Send HTTP POST request in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; class Main { public static void main(String[] args) throws Exception { URL url = new URL("https://postman-echo.com/post"); String postData = "foo1=bar1&foo2=bar2"; URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(postData.length())); try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) { dos.writeBytes(postData); } try (BufferedReader bf = new BufferedReader(new InputStreamReader( conn.getInputStream()))) { String line; while ((line = bf.readLine()) != null) { System.out.println(line); } } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; class Main { public static void main(String[] args) { try { URL url = new URL("https://postman-echo.com/post"); String postData = "foo1=bar1&foo2=bar2"; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(postData.length())); conn.setUseCaches(false); try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) { dos.writeBytes(postData); } try (BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream()))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } } catch (Exception e) { e.printStackTrace(); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.net.URI; class Main { public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpUriRequest httppost = RequestBuilder.post() .setUri(new URI("https://postman-echo.com/post")) .addParameter("foo1", "bar1") .addParameter("foo2", "bar2") .build(); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } finally { httpclient.close(); } } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)