How to Send Data in the Request Body Using HttpURLConnection in Java

Question

How can I send data in the request body using HttpURLConnection in Java?

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);

OutputStream os = connection.getOutputStream();
byte[] input = "your data here".getBytes("utf-8");
os.write(input, 0, input.length);
os.close();

Answer

When working with HttpURLConnection in Java, sending data in the request body is integral for operations such as POST requests. This guide walks you through the steps for correctly implementing this functionality.

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {
    public static void main(String[] args) throws Exception {
        String urlString = "http://example.com/api";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        String jsonInputString = "{\"name\":\"John\", \"age\":30}";

        try(OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);
    }
}

Causes

  • Understanding of HTTP methods (GET, POST) is needed.
  • Proper demonstration of setting request headers.

Solutions

  • Create a URL object pointing to the target endpoint.
  • Open an HttpURLConnection instance from the URL.
  • Set the request method to POST or another appropriate method.
  • Enable output for the connection to send request data.
  • Write the data to the connection's output stream.

Common Mistakes

Mistake: Not setting the request method to POST or another appropriate method.

Solution: Ensure you call connection.setRequestMethod("POST") before sending data.

Mistake: Missing or incorrect headers in the request.

Solution: Add necessary headers such as Content-Type if you are sending JSON data.

Mistake: Not closing the OutputStream, which might lead to memory leaks.

Solution: Use a try-with-resources statement to ensure the OutputStream is properly closed.

Helpers

  • HttpURLConnection
  • send data in request body
  • Java HttpURLConnection POST
  • HTTP request body Java
  • Java networking

Related Questions

⦿How to Handle Default Null Values in Annotations in Programming?

Learn how to effectively manage default null values in programming annotations with practical examples and common pitfalls.

⦿How to Add Custom User Details in Spring Security

Learn how to add custom user details to Spring Security enhancing user authentication and authorization features.

⦿How to Create an Application-Level OkHttpClient Instance in Android

Discover how to set up a global OkHttpClient instance for your Android application. Optimize HTTP requests with efficient networking.

⦿How to Retrieve Child Elements by Name Using the W3C DOM API in Java?

Learn how to use the W3C DOM API in Java to retrieve child elements by their name with clear explanations and code examples.

⦿What is the Difference Between `double` and `Double` in Programming?

Discover the key differences between double and Double types in programming languages and when to use each one in your code.

⦿How to Write to the Real STDOUT After Using System.setOut in Java?

Learn how to restore real STDOUT in Java after redirecting it with System.setOut. Follow our expert tips and code examples for clarity.

⦿What Are the Differences Between javax.security.cert.X509Certificate and java.security.cert.X509Certificate?

Explore the key differences between javax.security.cert.X509Certificate and java.security.cert.X509Certificate in Java including usage and features.

⦿Should Each Docker Image Include a Java Development Kit (JDK)?

Explore whether every Docker image should have a JDK installed including benefits alternatives and best practices.

⦿How to Resolve Issues with Java 8 Lambda Expressions in REST Services?

Learn how to troubleshoot and fix issues with Java 8 lambda expressions within REST services efficiently.

⦿How to Prevent PermGen Space Errors in NetBeans?

Learn effective strategies to prevent PermGen space errors in NetBeans by increasing memory allocation and optimizing settings.

© Copyright 2025 - CodingTechRoom.com