Open In App

How to use HttpURLConnection for sending HTTP POST requests in Java?

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

HttpURLConnection is a Java class that allows us to send HTTP requests and receive responses from servers. It is a powerful tool for communicating with common web servers used in Java development, including Android.

Here is an overview of its main features.

  • HTTP requests can be sent using several methods such as GET, POST, PUT, and DELETE.
  • Getting an HTTP response: Get the content, subject, and status code of the response.

In this article, we focus on sending an HTTP POST using HttpURLConnection to send data and get a response from the server.

HttpURLConnection for sending HTTP POST requests in Java

Here is an API example that we have used to test Java code. It just takes data and returns it. Now let’s see how to call API using HttpURLConnection in Java. To use HttpURLConnection, we need a working API that can return a response.

  • First, we need to set the API URL and establish a connection between the program and the API.
  • After successfully establishing the connection, we then call the API passing in the necessary input it needs.
  • After obtaining the response, we check if the API ran successfully by checking the responseCode.
  • If the responseCode is HTTP_OK (200), then we know that the API ran successfully without any errors.

Here is the Java Code for using HttpURLConnection to send “POST” Requests:

Java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class apiCall {
    public static void main(String[] args)
        throws URISyntaxException
    {

        // API URL
        String url = "http://127.0.0.1:5000";

        // JSON String which will be sent to the API.
        String data_to_send = "{\"data\": \"Sample Data\"}";

        try {
            URL obj = new URI(url).toURL(); // Making an object to point to the API URL

            // attempts to establish a connection to the URL represented by the obj.
            HttpURLConnection connection = (HttpURLConnection)obj.openConnection();

            // Set request method and enable writing to the connection
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // Set content type header,
            // input (Content-Type) is in JSON (application/json) format.
            connection.setRequestProperty("Content-Type", "application/json");

            // Calling the API and send request data
            // connection.getOutputStream() purpose is to obtain an output stream for sending data to the server.
            try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) {
                os.writeBytes(data_to_send);
                os.flush();
            }

            // Get response code and handle response
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // HTTP_OK or 200 response code generally means that the server ran successfully without any errors
                StringBuilder response = new StringBuilder();

                // Read response content
                // connection.getInputStream() purpose is to obtain an input stream for reading the server's response.
                try (
                    BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line); // Adds every line to response till the end of file.
                    }
                }
                System.out.println("Response: " + response.toString());
            }
            else {
                System.out.println("Error: HTTP Response code - " + responseCode);
            }
            connection.disconnect();
        }
        catch (IOException e) {
            // If any error occurs during api call it will go into catch block
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
}

Output:

Response: {  "message": "You sent the data: Sample Data"}

Below we can see the output video of testing the API in POSTMAN tool:

Testing API in POSTMAN

Explanation of the Program:

  • The code configures the target URL and JSON String to be passed to the API Call. It then uses HttpURLConnection to create a connection object to the URL.
  • This sets the request method to “POST” and provides input for the connection. It also changes the Content-Type header to “application/json” to specify the data type.
  • The code uses connection.getOutputStream() to get an output stream and write data using DataOutputStream. It then flows the stream to ensure that the data is sent over the connection.
  • Attempt to read a response from the server using connection.getInputStream(). It reads the response line by line and creates a response string.
  • Once we get the response successfully, we print it in the console.

HttpURLConnection Methods used in the code:

Method

Use

openConnection()

Inherited from URLConnection class, its purpose is to create a new connection object targeting a specific URL provided by the user.

setRequestMethod(String method)

This method is used to set the request type (GET, POST, PUT etc)

setDoOutput(boolean doOutput)

Enables or disables the request body for the connection.

setRequestProperty(String key, String value)

Sets the type of the request header field.

getOutputStream()

Returns an output stream that writes into the connection.

getResponseCode()

Returns the responseCode from the server’s response.

getInputStream()

Returns an input stream object for reading the response from the server.

disconnect()

closes the connection to the server.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads