Java > Java Networking > HTTP and Web Services > Using HttpURLConnection

HTTP POST Request with JSON payload using HttpURLConnection

This code demonstrates how to send a JSON payload using a HTTP POST request. This is commonly used for creating or updating resources on a server. The example shows how to construct a JSON string, set the appropriate headers, and write the JSON data to the output stream of the HttpURLConnection.

Code Snippet

This code creates a URL object pointing to the desired POST endpoint. It then opens an HttpURLConnection. The setRequestMethod("POST") sets the request method to POST. The setDoOutput(true) method enables writing to the output stream. The setRequestProperty() method sets the Content-Type and Accept headers to application/json, indicating that we are sending and expecting JSON data. A JSONObject is created and populated with data. The JSON object is then converted to a byte array and written to the output stream of the connection. The response code is retrieved, and if it's HTTP_OK or HTTP_CREATED, the response body is read and printed to the console. Finally, the connection is disconnected.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class HttpPostExample {

    public static void main(String[] args) {
        try {
            URL url = new URL("https://httpbin.org/post"); // Replace with your desired POST endpoint
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set the request method to POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // Enable writing to the output stream

            // Set request headers
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            // Create JSON payload
            JSONObject jsonPayload = new JSONObject();
            jsonPayload.put("name", "John Doe");
            jsonPayload.put("age", 30);

            // Write JSON payload to the output stream
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonPayload.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // Read the response body
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // Print the response body
                System.out.println("Response Body: " + response.toString());
            } else {
                System.out.println("POST request failed: " + responseCode);
            }

            connection.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Concepts Behind the Snippet

This snippet builds upon the HTTP concepts demonstrated in the GET example. It introduces the POST method, which is used to send data to the server to create or update a resource. It also demonstrates how to send data in the JSON format, which is a common standard for data interchange on the web. The Content-Type header tells the server the format of the data being sent, while the Accept header tells the server the format of the data the client is willing to receive. Using a JSON library (in this case, org.json) makes creating and manipulating JSON data easier. Other popular JSON libraries are Gson and Jackson.

Real-Life Use Case

Imagine you're building a user registration feature for your web application. When a user submits the registration form, your application could use this snippet to send the user's data (e.g., username, email, password) to the server as a JSON payload via a POST request. The server would then process the data and create a new user account.

Best Practices

  • Use Try-with-resources: This snippet demonstrates the use of the try-with-resources statement when handling output streams. This ensures that the stream is automatically closed, even if an exception occurs.
  • Error Handling: As with the GET example, proper error handling is crucial. Check the response code and handle different error scenarios gracefully.
  • Character Encoding: Specify the character encoding (e.g., UTF-8) when converting the JSON string to bytes to ensure proper encoding of special characters.
  • Validate Input: Before sending the JSON payload, validate the input data to prevent errors on the server side.

Interview Tip

Be prepared to discuss the differences between GET and POST requests and their respective use cases. Also, understand how to handle JSON data in Java and how to set the appropriate headers for different content types. Be able to explain different HTTP status codes and what they indicate.

When to use them

Use the POST method with a JSON payload when you need to send data to the server to create a new resource, update an existing resource, or perform some other action that modifies the server's state. Sending the data in JSON format is suitable when the server expects JSON data, which is common in modern web APIs.

Memory Footprint

The memory footprint depends on the size of the JSON payload and the size of the response body. Smaller payloads and responses will result in lower memory usage. Proper resource management (closing streams) is essential for minimizing memory leaks.

Alternatives

Alternatives to HttpURLConnection for POST requests with JSON payloads are the same as for GET requests:

  • HttpClient (Java 11+):
  • OkHttp:
  • Retrofit:
  • Apache HttpClient:

Pros

  • Built-in: It's part of the Java standard library.
  • Direct Control: Allows precise control over the HTTP request.

Cons

  • More Code: Requires more code compared to using higher-level HTTP client libraries.
  • Manual Handling: You have to manually handle details like setting headers and writing the payload.

FAQ

  • What does 'connection.setDoOutput(true)' do?

    It tells the HttpURLConnection that you intend to write data to the connection's output stream, which is necessary for POST and PUT requests.
  • Why do I need to set the 'Content-Type' header?

    The 'Content-Type' header informs the server about the format of the data you are sending in the request body. Setting it to 'application/json' indicates that the data is in JSON format.
  • What if the server returns a different status code than 200 or 201?

    You should handle different status codes appropriately. For example, 400 (Bad Request) indicates that the client sent invalid data, 401 (Unauthorized) indicates that authentication is required, and 500 (Internal Server Error) indicates that the server encountered an error.