How to Send an HTTP POST Request in Java

Question

How can I send an HTTP POST request to a server in Java?

URL url = new URL("http://www.example.com/page.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
byte[] input = "id=10".getBytes("utf-8");
os.write(input, 0, input.length);
os.close();

Answer

Sending an HTTP POST request in Java can be accomplished using the HttpURLConnection class. This allows you to connect to a web server and send data, such as parameters, to be processed by a server-side script like PHP.

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

public class HttpPostExample {
    public static void main(String[] args) throws Exception {
        // Define the URL
        URL url = new URL("http://www.example.com/page.php");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Set up connection properties
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        // Prepare data to send
        String urlParameters = "id=10";

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

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

Causes

  • Not setting the request method properly to POST.
  • Forgetting to enable output on the connection with setDoOutput(true).
  • Failing to handle encoding and converting the parameters appropriately.

Solutions

  • Use HttpURLConnection for handling HTTP requests.
  • Set the request method to POST using setRequestMethod("POST").
  • Prepare the output stream correctly and write the parameters using the OutputStream.

Common Mistakes

Mistake: Not handling exceptions properly during URL connection.

Solution: Surround your connection code with try-catch blocks to handle IOException.

Mistake: Sending data without a proper content type.

Solution: Set the content type using connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded").

Helpers

  • Java HTTP POST request
  • send POST request Java
  • Java HttpURLConnection
  • Java web programming POST
  • HTTP requests in Java

Related Questions

⦿How to Resolve the 'javax.xml.bind Package Does Not Exist' Error in Java 11?

Learn how to fix the javax.xml.bind package not found error when deserializing XML with JAXB in Java 11. Stepbystep guide and solutions included.

⦿Can You Use the instanceof Operator in a Switch Statement in Java?

Learn if you can use the instanceof operator in a Java switch statement and explore alternatives with code examples.

⦿How to Convert a Byte Array to a String and Back in Java?

Learn how to accurately convert byte arrays to strings and back in Java including handling negative byte values for correct conversions.

⦿Understanding the Differences Between Java System Properties and Environment Variables

Explore the key differences between Java system properties System.getProperties and environment variables System.getenv in the JVM.

⦿How to Retrieve the User's Home Directory in Java Across All Platforms?

Learn how to find the users home directory in Java with crossplatform compatibility. Example code included for Windows OS X and Linux.

⦿How to Prevent Constructor Overload in Dependency Injection?

Learn effective strategies to manage constructor overload in Dependency Injection using best practices for IoC.

⦿How to Define a Java 8 Lambda Function Without Arguments or Return Type?

Learn how to simplify Java 8 lambda functions using functional interfaces without unnecessary Void type parameters for cleaner code.

⦿Is It Bad Practice to Call System.gc() in Java?

Discover why manually calling System.gc is often discouraged in Java programming and understand when if ever it might be acceptable.

⦿Understanding Java Heap Memory: Young, Old, and Permanent Generations

Explore the concepts of Young Old and Permanent Generations in Java heap memory management and their interactions for optimized performance.

⦿How to Create a Deep Copy of an Object in JavaScript?

Learn how to implement a deep copy function in JavaScript ensuring the original object and clone share no references.

© Copyright 2025 - CodingTechRoom.com