How to Send HTTP Parameters Using POST Method in Java

Question

How can I modify my existing Java code to send HTTP parameters using the POST method instead of GET?

void sendRequest(String request, String httpMethod) {
    URL url = new URL("http://example.com/index.php");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(httpMethod);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    // Adding parameters if the request method is POST
    if (httpMethod.equals("POST")) {
        String params = "param1=a&param2=b&param3=c"; // Your parameters here
        OutputStream os = connection.getOutputStream();
        os.write(params.getBytes("UTF-8"));
        os.close();
    }
    connection.connect();
}

Answer

When sending HTTP requests in Java, specifically when utilizing the `HttpURLConnection` class, it is critical to properly set up your connection to handle different HTTP methods such as GET and POST effectively. Here’s how to adapt your existing GET method to support sending parameters via POST as well.

void sendRequest(String request, String httpMethod) {
    URL url = new URL("http://example.com/index.php");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(httpMethod);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    // Adding parameters if the request method is POST
    if (httpMethod.equals("POST")) {
        String params = "param1=a&param2=b&param3=c"; // Your parameters here
        OutputStream os = connection.getOutputStream();
        os.write(params.getBytes("UTF-8"));
        os.close();
    }
    connection.connect();
}

Causes

  • The initial setup used the GET method, which appends parameters in the URL.
  • Switching to POST requires sending parameters in the request body instead of the URL.

Solutions

  • Modify the header to set the `Content-Type` to `application/x-www-form-urlencoded` for POST requests.
  • Use an `OutputStream` to write the parameters in the request body when the method is POST.

Common Mistakes

Mistake: Forgetting to set `setDoOutput(true)` before sending a POST request.

Solution: Always set `setDoOutput(true)` for POST requests.

Mistake: Not properly encoding parameters when sending them via POST.

Solution: URL-encode the parameters using `URLEncoder.encode()` as needed.

Helpers

  • Java HTTP POST request
  • Java HttpURLConnection POST
  • send parameters via POST Java
  • Java POST method example

Related Questions

⦿Understanding the Differences Between Hibernate and Spring Data JPA

Explore the key differences between Hibernate and Spring Data JPA including performance considerations and when to use Spring JDBC Template.

⦿How to Initialize All Elements of an Array to Zero in Java Without a Loop?

Learn how to efficiently initialize a Java array to zero without using loops. Discover shortcuts and best practices for array initialization.

⦿How to Use Servlets with AJAX to Update Content on the Current Page

Learn how to effectively use servlets and AJAX to enable dynamic content updates on your web pages without reloading.

⦿How to Increase Java Heap Size on Windows Server 2003

Learn how to increase the maximum heap size for Java applications on a 64bit Windows Server 2003 system.

⦿How to Retrieve the Current Machine's IP Address in Java?

Learn how to obtain your machines IP address in Java including public and local IP retrieval methods and common pitfalls.

⦿How to Resolve GSON's "Expected BEGIN_OBJECT but was BEGIN_ARRAY" Exception?

Learn how to fix GSONs Expected BEGINOBJECT but was BEGINARRAY error when parsing JSON arrays in Java. Find stepbystep solutions and code examples

⦿What is the Performance Impact of Variable Declarations Inside vs. Outside a Loop in Java?

Explore the performance implications of declaring variables before or inside loops in Java. Understand their differences and best practices.

⦿Understanding the Maximum Value of Integers in C and Java

Discover the differences in maximum integer values between C and Java despite both using 32 bits. Learn about data types and their ranges.

⦿How to Replace Multiple Spaces with a Single Space and Trim Leading/Trailing Spaces in Java

Learn how to replace multiple spaces with a single space and trim leadingtrailing spaces in Java strings with examples.

⦿Why Are Interface Variables Static and Final by Default in Java?

Discover why interface variables in Java are static and final by default including the implications and benefits of this design.

© Copyright 2025 - CodingTechRoom.com