Java

HttpClient — POST JSON

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
POST a JSON body with `HttpRequest.BodyPublishers.ofString` + the right Content-Type. Pair with Jackson / Gson to serialize objects to JSON.
Java
Raw
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

class Demo {
    static final HttpClient client = HttpClient.newHttpClient();

    HttpResponse<String> postJson(String url, String token, String bodyJson) throws Exception {
        var req = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .POST(HttpRequest.BodyPublishers.ofString(bodyJson))
            .header("Content-Type",  "application/json")
            .header("Accept",        "application/json")
            .header("Authorization", "Bearer " + token)
            .timeout(Duration.ofSeconds(15))
            .build();

        return client.send(req, HttpResponse.BodyHandlers.ofString());
    }

    public static void main(String[] args) throws Exception {
        var body = """
            { "name": "Alice", "email": "a@x.com" }
            """;
        var r = new Demo().postJson("https://api.example.com/users",
            System.getenv("API_TOKEN"), body);
        System.out.println(r.statusCode() + " " + r.body());
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.