Java
HTTP POST Request
Web Development
Programming
Coding

Sending HTTP POST Request In Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Sending HTTP POST requests in Java is a common requirement for many applications. Java, being a robust programming language, provides multiple ways to handle HTTP requests. The following are some methods and libraries you can use to perform HTTP POST requests:

1. java.net.HttpURLConnection

The java.net.HttpURLConnection class allows Java applications to communicate with web servers using HTTP. To send a POST request using this class, you follow these steps:

  1. Create a URL object.
  2. Open a connection using the URL object.
  3. Set the request method of the HttpURLConnection instance to POST.
  4. Set the request headers as necessary, such as Content-Type.
  5. Write the data (payload) to the connection output stream.
  6. Read the response from the server.

Example:

java
1URL url = new URL("http://example.com/api/resource");
2HttpURLConnection con = (HttpURLConnection) url.openConnection();
3con.setRequestMethod("POST");
4con.setRequestProperty("Content-Type", "application/json; utf-8");
5con.setDoOutput(true);
6
7String jsonInputString = "{\"name\": \"John\", \"age\": 30}";
8
9try(OutputStream os = con.getOutputStream()) {
10    byte[] input = jsonInputString.getBytes("utf-8");
11    os.write(input, 0, input.length);           
12}
13
14try(BufferedReader br = new BufferedReader(
15  new InputStreamReader(con.getInputStream(), "utf-8"))) {
16    StringBuilder response = new StringBuilder();
17    String responseLine = null;
18    while ((responseLine = br.readLine()) != null) {
19        response.append(responseLine.trim());
20    }
21    System.out.println(response.toString());
22}

2. Apache HttpClient

Apache HttpClient is a highly configurable library that can handle HTTP connections. This is more flexible and powerful than HttpURLConnection and supports HTTP/2 as well.

Example:

java
1CloseableHttpClient httpClient = HttpClients.createDefault();
2HttpPost httpPost = new HttpPost("http://example.com/api/resource");
3httpPost.setEntity(new StringEntity("{\"name\": \"John\"}"));
4
5HttpResponse response = httpClient.execute(httpPost);
6HttpEntity entity = response.getEntity();
7if (entity != null) {
8    String result = EntityUtils.toString(entity);
9    System.out.println(result);
10}

3. Spring RestTemplate

For developers using the Spring Framework, RestTemplate offers a straightforward way to send HTTP requests.

Example:

java
1RestTemplate restTemplate = new RestTemplate();
2HttpHeaders headers = new HttpHeaders();
3headers.setContentType(MediaType.APPLICATION_JSON);
4HttpEntity<String> request = new HttpEntity<>(jsonInputString, headers);
5
6ResponseEntity<String> response = restTemplate.postForEntity("http://example.com/api/resource", request, String.class);
7System.out.println(response.getBody());

Summary Table

Method/ClassLibrary/PackageEase of UseFlexibilitySuitable for
HttpURLConnectionjava.netSimpleLowSmall-scale applications
HttpClientorg.apache.httpcomponentsModerateHighLarge-scale applications requiring customization
RestTemplateorg.springframework.web.clientHighModerateSpring-based applications

Additional Considerations

  • Handling Exceptions: It's important to handle IOExceptions and other exceptions to ensure your application remains robust.
  • Connection Timeout: Always set timeouts to prevent your application from hanging indefinitely.
  • Thread Safety: java.net.HttpURLConnection is not thread-safe whereas HttpClient and RestTemplate offer thread-safe components.

Conclusion

Choosing the right method to send HTTP POST requests in Java depends largely on the specific needs of your application, such as required customization levels and the scale of usage. While HttpURLConnection provides a built-in method with the JDK, using Apache HttpClient or Spring's RestTemplate can provide additional flexibility and capabilities especially suitable for more complex applications.


Course illustration
Course illustration

All Rights Reserved.