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());PUT request example
Replacing a resource with PUT:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users/123"))
.header("Content-Type", "application/json")
.PUT(HttpRequest.BodyPublishers.ofString("{\"name\":\"John Updated\"}"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());DELETE request example
Deleting a resource:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users/123"))
.header("Authorization", "Bearer YOUR_TOKEN")
.DELETE()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());Error handling
HttpClient does not throw on 4xx/5xx. Check response.statusCode() and handle accordingly. Use HttpClient.Version.HTTP_2 for HTTP/2.
Try it in Send Web Request
Test your API in Send Web Request first. Build the request in the browser, then implement it in Java.
Open Send Web RequestOther libraries you can try
- Python:
Requests— simple and popular HTTP library,HTTPX— async-capable HTTP client - JavaScript:
Axios— promise-based HTTP client,node-fetch— Fetch API for Node.js - Ruby:
HTTParty— simple HTTP client,Faraday— flexible HTTP library,RestClient— lightweight REST client - Java:
OkHttp— efficient HTTP client,Apache HttpClient— feature-rich library - C#:
RestSharp— simple REST client,Flurl— fluent HTTP library - Go (Golang):
resty— simple HTTP client,grequests— goroutine-based requests - PHP:
Guzzle— popular PHP HTTP client,Symfony HttpClient— component-based HTTP client