Java HttpClient — GET and POST Requests
Make HTTP requests with Java 11+ HttpClient: GET, POST JSON, async calls, and response handling.
import java.net.URI;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
public class HttpClientDemo {
private static final HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
// GET request
public static String get(String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("HTTP " + response.statusCode());
}
return response.body();
}
// POST JSON
public static String postJson(String url, String json) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
return response.body();
}
// Async GET
public static void asyncGet(String url) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
public static void main(String[] args) throws Exception {
String data = get("https://api.example.com/users");
System.out.println(data);
String result = postJson("https://api.example.com/users",
"{\"name\": \"Alice\", \"email\": \"alice@test.com\"}");
System.out.println(result);
}
}Use Cases
- Calling REST APIs from Java applications
- Sending JSON payloads to web services
- Non-blocking async HTTP calls
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Spring Boot REST Controller with CRUD
Create a complete REST API with Spring Boot: GET, POST, PUT, DELETE with validation and error handling.
Best for: Building RESTful APIs with Spring Boot
Spring Boot Global Exception Handler
Centralized error handling with @ControllerAdvice for validation errors, 404s, and custom exceptions.
Best for: Consistent error responses across all endpoints
Java Built-in HTTP Server
Create a lightweight HTTP server with com.sun.net.httpserver: routing, JSON responses, file serving.
Best for: Lightweight HTTP servers for testing and prototyping
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews