Java
HTTP Parameters
POST Method
Web Development
Coding Tutorial

Java - sending HTTP parameters via POST method easily

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Sending data with an HTTP POST request is a routine task in Java applications that talk to web forms, REST APIs, and authentication endpoints. The main point is not just opening a connection, but encoding parameters correctly, setting the right content type, and reading the server response safely.

Use the Modern Java HttpClient

If you are on Java 11 or newer, the easiest standard-library solution is java.net.http.HttpClient. For classic form parameters, you usually send the body as application/x-www-form-urlencoded.

java
1import java.io.IOException;
2import java.net.URI;
3import java.net.URLEncoder;
4import java.net.http.HttpClient;
5import java.net.http.HttpRequest;
6import java.net.http.HttpResponse;
7import java.nio.charset.StandardCharsets;
8import java.util.Map;
9import java.util.stream.Collectors;
10
11public class FormPostExample {
12    private static String formEncode(Map<String, String> params) {
13        return params.entrySet().stream()
14                .map(entry ->
15                        URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) +
16                        "=" +
17                        URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
18                .collect(Collectors.joining("&"));
19    }
20
21    public static void main(String[] args) throws IOException, InterruptedException {
22        HttpClient client = HttpClient.newHttpClient();
23
24        String body = formEncode(Map.of(
25                "username", "alice",
26                "password", "p@ss word"
27        ));
28
29        HttpRequest request = HttpRequest.newBuilder()
30                .uri(URI.create("https://example.com/login"))
31                .header("Content-Type", "application/x-www-form-urlencoded")
32                .POST(HttpRequest.BodyPublishers.ofString(body))
33                .build();
34
35        HttpResponse<String> response = client.send(
36                request,
37                HttpResponse.BodyHandlers.ofString()
38        );
39
40        System.out.println("Status: " + response.statusCode());
41        System.out.println("Body: " + response.body());
42    }
43}

The critical part is the encoding step. Parameters such as spaces, @, and & must be percent-encoded, otherwise the server may parse them incorrectly.

Form Parameters Versus JSON

A lot of confusion comes from mixing up two different styles of POST request:

  • form parameters sent as application/x-www-form-urlencoded
  • JSON payloads sent as application/json

If the server expects form fields, use form encoding as shown above. If the server expects JSON, do not try to squeeze JSON text into form encoding.

java
1import java.io.IOException;
2import java.net.URI;
3import java.net.http.HttpClient;
4import java.net.http.HttpRequest;
5import java.net.http.HttpResponse;
6
7public class JsonPostExample {
8    public static void main(String[] args) throws IOException, InterruptedException {
9        HttpClient client = HttpClient.newHttpClient();
10
11        String json = """
12                {
13                  "name": "Alice",
14                  "email": "[email protected]"
15                }
16                """;
17
18        HttpRequest request = HttpRequest.newBuilder()
19                .uri(URI.create("https://example.com/api/users"))
20                .header("Content-Type", "application/json")
21                .header("Accept", "application/json")
22                .POST(HttpRequest.BodyPublishers.ofString(json))
23                .build();
24
25        HttpResponse<String> response = client.send(
26                request,
27                HttpResponse.BodyHandlers.ofString()
28        );
29
30        System.out.println(response.statusCode());
31        System.out.println(response.body());
32    }
33}

The request body and the Content-Type header must agree. A surprising number of 400 and 415 responses come from sending the right data in the wrong format.

Reading Responses and Handling Errors

It is not enough to send the request and print the status code. Real code usually needs to handle unsuccessful responses explicitly.

java
1if (response.statusCode() >= 200 && response.statusCode() < 300) {
2    System.out.println("Request succeeded");
3} else {
4    System.err.println("Request failed with status " + response.statusCode());
5    System.err.println(response.body());
6}

This matters because many APIs return useful error messages in the response body even when the status code indicates failure. If you ignore that body, debugging becomes much slower.

You should also think about timeouts for production code. A network call without a timeout can block longer than expected:

java
1HttpRequest request = HttpRequest.newBuilder()
2        .uri(URI.create("https://example.com/login"))
3        .timeout(java.time.Duration.ofSeconds(10))
4        .header("Content-Type", "application/x-www-form-urlencoded")
5        .POST(HttpRequest.BodyPublishers.ofString(body))
6        .build();

Older Code: HttpURLConnection

If you are maintaining older Java code, you may still see HttpURLConnection. It works, but it is more verbose and less pleasant than the modern client API. The same principles still apply: encode parameters, set doOutput, write the body, and read the response carefully.

For new code on supported Java versions, HttpClient is usually the cleaner choice.

Common Pitfalls

  • Building the body as key=value&key2=value2 without URL-encoding the keys and values.
  • Sending JSON while keeping the content type as application/x-www-form-urlencoded, or the reverse.
  • Ignoring non-2xx responses and losing the server's error message.
  • Forgetting timeouts for network calls that may hang longer than expected.
  • Using POST parameters for sensitive data over plain HTTP instead of HTTPS.

Summary

  • On modern Java, java.net.http.HttpClient is the easiest standard way to send POST requests.
  • Use URLEncoder and application/x-www-form-urlencoded for classic HTTP parameters.
  • Use application/json only when the server expects a JSON body.
  • Check both the status code and the response body when handling errors.
  • Add timeouts and prefer HTTPS so the request is robust and secure.

Course illustration
Course illustration

All Rights Reserved.