Skip to main content
Send Web Request

How to Make an HTTP Request with Java

Java 11+ includes HttpClient in the standard library. For older versions, use libraries like OkHttp or Apache HttpClient.

GET request example

Making a GET request to fetch data with custom headers:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/users"))
    .header("Accept", "application/json")
    .header("Authorization", "Bearer YOUR_TOKEN")
    .GET()
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

POST request example

Making a POST request to send JSON data:

HttpClient client = HttpClient.newHttpClient();
String body = "{"name":"John","email":"john@example.com"}";
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/users"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

Other libraries you can try