Java HTTP Requests
A Java HTTP request is built with HttpRequest.newBuilder() and sent with an HttpClient. The request describes everything the server needs: the URI, the HTTP method (GET, POST, PUT, DELETE and others), the headers and, for methods that send data, a body.
This lesson shows how to send each kind of HTTP request in Java: GET requests with query parameters, POST requests with JSON and form data, PUT, PATCH and DELETE requests, custom headers, file uploads and request timeouts. It ends with a small REST client that performs all CRUD operations against an API.
How a Java HTTP Request Is Built
HttpRequest.newBuilder() returns a builder. You chain methods to describe the request and finish with build(), which creates an immutable HttpRequest you can send as often as you like.
| Builder method | Purpose |
|---|---|
uri(URI) | The address to send the request to (or pass it to newBuilder(uri)) |
GET(), DELETE(), HEAD() | Methods without a body (HEAD() since Java 18) |
POST(BodyPublisher), PUT(BodyPublisher) | Methods with a body |
method(String, BodyPublisher) | Any other method, such as PATCH |
header(name, value) | Add a header (can repeat the same name) |
headers(name1, value1, name2, value2, ...) | Add several headers at once |
setHeader(name, value) | Set a header, replacing earlier values |
timeout(Duration) | Fail if the response takes longer than this |
version(HttpClient.Version) | Use a specific HTTP version for this request |
build() | Create the immutable HttpRequest |
The body publisher (HttpRequest.BodyPublishers) turns Java data into the bytes of the request body.
A Local API Server for the Examples
To keep every example runnable offline, they all send requests to a small server on http://localhost:8091. Save it as ApiServer.java next to the examples.
/echoreplies with a description of the request it received, so you can see exactly what Java sent./notesis a tiny REST API that stores notes in memory and requires the headerAuthorization: Bearer demo-token.
// FILE: ApiServer.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
// A small local HTTP API on http://localhost:8091 used by the examples
public class ApiServer {
private static final Map<Integer, String> NOTES = new TreeMap<>();
private static final AtomicInteger NEXT_ID = new AtomicInteger(1);
public static HttpServer start() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8091), 0);
server.createContext("/echo", ApiServer::echo);
server.createContext("/notes", ApiServer::notes);
server.start();
return server;
}
// Describe the request: method, path, query, some headers and the body
private static void echo(HttpExchange ex) throws IOException {
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
var h = ex.getRequestHeaders();
String text = "method=" + ex.getRequestMethod()
+ "\nquery=" + ex.getRequestURI().getRawQuery()
+ "\ncontent-type=" + h.getFirst("Content-Type")
+ "\naccept=" + h.getFirst("Accept")
+ "\nx-request-id=" + h.get("X-Request-Id")
+ "\nbody=" + body;
send(ex, 200, text);
}
// A tiny notes REST API: GET, POST, PUT, PATCH, DELETE
private static synchronized void notes(HttpExchange ex) throws IOException {
if (!"Bearer demo-token".equals(ex.getRequestHeaders().getFirst("Authorization"))) {
send(ex, 401, "{\"error\":\"missing or wrong token\"}");
return;
}
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
String[] parts = ex.getRequestURI().getPath().split("/"); // ["", "notes", "{id}"]
Integer id = parts.length > 2 ? Integer.valueOf(parts[2]) : null;
switch (ex.getRequestMethod()) {
case "GET" -> {
if (id == null) send(ex, 200, NOTES.values().toString());
else if (NOTES.containsKey(id)) send(ex, 200, NOTES.get(id));
else send(ex, 404, "{\"error\":\"note " + id + " not found\"}");
}
case "POST" -> {
int newId = NEXT_ID.getAndIncrement();
NOTES.put(newId, "{\"id\":" + newId + "," + body.substring(1));
ex.getResponseHeaders().add("Location", "/notes/" + newId);
send(ex, 201, NOTES.get(newId));
}
case "PUT", "PATCH" -> {
if (id == null || !NOTES.containsKey(id)) { send(ex, 404, "{\"error\":\"not found\"}"); return; }
NOTES.put(id, "{\"id\":" + id + "," + body.substring(1));
send(ex, 200, NOTES.get(id));
}
case "DELETE" -> {
ex.sendResponseHeaders(NOTES.remove(id) != null ? 204 : 404, -1); // 204 = no content
ex.close();
}
default -> send(ex, 405, "{\"error\":\"method not allowed\"}");
}
}
private static void send(HttpExchange ex, int status, String text) throws IOException {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
boolean head = ex.getRequestMethod().equals("HEAD"); // HEAD responses have no body
ex.sendResponseHeaders(status, head ? -1 : bytes.length);
if (!head) ex.getResponseBody().write(bytes);
ex.close();
}
}
When you work with a real API, only the URIs change; the request code stays the same.
Sending a GET Request with Query Parameters
A GET request asks for data and has no body. Parameters go in the query string of the URI. Encode each value with URLEncoder so spaces and symbols are sent correctly.
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class GetRequest {
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
String search = "wireless mouse & pad";
String query = "q=" + URLEncoder.encode(search, StandardCharsets.UTF_8) + "&page=2";
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8091/echo?" + query))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
} finally {
server.stop(0);
}
}
}
Output:
200
method=GET
query=q=wireless+mouse+%26+pad&page=2
content-type=null
accept=application/json
x-request-id=null
body=
How it works:
URLEncoder.encodeturns the spaces into+and&into%26, so the server sees oneqvalue, not two parameters.header("Accept", "application/json")tells the server which response format you want.- A GET request has no body and no
Content-Type, as the echo shows.
Sending a POST Request with a JSON Body
A POST request sends data to the server, usually to create something. Pass the body to POST() with a body publisher, and set the Content-Type header so the server knows the format.
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class PostJson {
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
// A text block keeps the JSON readable
String json = """
{"name":"Asha","email":"asha@example.com","course":"Java"}""";
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8091/echo"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
System.out.println("Body length: " + request.bodyPublisher().orElseThrow().contentLength() + " bytes");
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
} finally {
server.stop(0);
}
}
}
Output:
Body length: 58 bytes
method=POST
query=null
content-type=application/json
accept=null
x-request-id=null
body={"name":"Asha","email":"asha@example.com","course":"Java"}
How it works:
BodyPublishers.ofString(json)encodes the text as UTF-8 bytes. Java sets theContent-Lengthheader automatically from the publisher.request.bodyPublisher()returns the publisher, andcontentLength()shows the body size in bytes.- Java does not guess the
Content-Type; always set it yourself, or many APIs reject the request.
Note: Java has no built-in JSON library. Small examples like this one write JSON as text. In real projects, use a library such as Jackson or Gson to convert objects to JSON and back.
Sending HTML Form Data with POST
HTML forms send data as application/x-www-form-urlencoded: key=value pairs joined with &, with each key and value URL-encoded. Many login and payment APIs expect this format.
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class PostForm {
// Build "key1=value1&key2=value2" with every part encoded
static String formBody(Map<String, String> fields) {
return fields.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
+ URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
}
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
Map<String, String> fields = new LinkedHashMap<>();
fields.put("username", "ravi.kumar");
fields.put("password", "p@ss word!");
fields.put("remember", "true");
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8091/echo"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(formBody(fields)))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
response.body().lines()
.filter(line -> line.startsWith("content-type") || line.startsWith("body"))
.forEach(System.out::println);
} finally {
server.stop(0);
}
}
}
Output:
content-type=application/x-www-form-urlencoded
body=username=ravi.kumar&password=p%40ss+word%21&remember=true
How it works:
formBody()encodes each key and value separately, so@becomes%40, the space becomes+and!becomes%21.- A
LinkedHashMapkeeps the fields in the order they were added. - The body is the same format a browser sends when you submit an HTML form.
PUT, PATCH, DELETE and HEAD Requests
REST APIs use different methods for different actions on a resource.
| Method | Meaning | Body? | Builder call |
|---|---|---|---|
| GET | Read a resource | No | GET() |
| POST | Create a resource | Yes | POST(publisher) |
| PUT | Replace a resource | Yes | PUT(publisher) |
| PATCH | Change part of a resource | Yes | method("PATCH", publisher) |
| DELETE | Remove a resource | No | DELETE() |
| HEAD | Like GET, but headers only | No | HEAD() |
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
public class OtherMethods {
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
URI echo = URI.create("http://localhost:8091/echo");
HttpRequest[] requests = {
HttpRequest.newBuilder(echo).PUT(BodyPublishers.ofString("{\"price\":999}")).build(),
HttpRequest.newBuilder(echo).method("PATCH", BodyPublishers.ofString("{\"stock\":5}")).build(),
HttpRequest.newBuilder(echo).DELETE().build(),
HttpRequest.newBuilder(echo).HEAD().build()
};
try (HttpClient client = HttpClient.newHttpClient()) {
for (HttpRequest request : requests) {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String echoedBody = response.body().lines()
.filter(line -> line.startsWith("body=")).findFirst().orElse("(no response body)");
System.out.printf("%-6s -> %d, %s%n", request.method(), response.statusCode(), echoedBody);
}
} finally {
server.stop(0);
}
}
}
Output:
PUT -> 200, body={"price":999}
PATCH -> 200, body={"stock":5}
DELETE -> 200, body=
HEAD -> 200, (no response body)
How it works:
PUT()andmethod("PATCH", ...)send a body just likePOST(). The builder has noPATCH()method, so you use the generalmethod().DELETE()sends no body, so the server echoes an empty one.- A
HEADresponse never has a body, so the server sends only the status and headers (inApiServer,sendResponseHeaders(status, -1)means "no body"). Use it to check whether a resource exists. request.method()returns the method name of a built request.
Adding Headers to an HTTP Request
Headers carry extra information: authentication tokens, the format you accept, a request ID for tracing, and more.
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class RequestHeaders {
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8091/echo"))
.headers("Accept", "text/plain", // several headers at once
"User-Agent", "GoCourseApp/1.0")
.header("X-Request-Id", "req-001") // header() adds a value...
.header("X-Request-Id", "req-002") // ...so this header now has two values
.setHeader("Accept", "application/json") // setHeader() replaces the value
.build();
System.out.println("Headers in the request: " + request.headers().map());
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
response.body().lines()
.filter(line -> line.startsWith("accept") || line.startsWith("x-request-id"))
.forEach(System.out::println);
} finally {
server.stop(0);
}
// Some headers are controlled by the client and cannot be set
try {
HttpRequest.newBuilder(URI.create("http://localhost:8091/echo")).header("Host", "evil.example.com");
} catch (IllegalArgumentException e) {
System.out.println("Host header: " + e.getMessage());
}
}
}
Output:
Headers in the request: {Accept=[application/json], User-Agent=[GoCourseApp/1.0], X-Request-Id=[req-001, req-002]}
accept=application/json
x-request-id=[req-001, req-002]
Host header: restricted header name: "Host"
How it works:
headers(...)takes name/value pairs.header()adds a value, soX-Request-Idends up with two values;setHeader()replaces all values ofAccept.request.headers().map()shows the headers the request will send.Host,Connection,Content-Length,ExpectandUpgradeare restricted: the client sets them itself, and setting them throwsIllegalArgumentException.
Body Publishers: Strings, Bytes and Files
Besides ofString, the BodyPublishers class can send bytes, files and streams.
| Body publisher | Sends |
|---|---|
ofString(String) | Text, encoded as UTF-8 |
ofString(String, Charset) | Text in another encoding |
ofByteArray(byte[]) | Raw bytes |
ofFile(Path) | The content of a file, read while sending |
ofInputStream(Supplier<InputStream>) | Data from a stream |
noBody() | An empty body |
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
public class UploadFile {
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
// Create a small CSV file to upload
Path report = Files.createTempFile("sales", ".csv");
Files.writeString(report, "month,amount\nJan,42000\nFeb,51500");
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest upload = HttpRequest.newBuilder(URI.create("http://localhost:8091/echo"))
.header("Content-Type", "text/csv")
.timeout(Duration.ofSeconds(10))
.POST(BodyPublishers.ofFile(report))
.build();
System.out.println("Uploading " + upload.bodyPublisher().orElseThrow().contentLength() + " bytes");
HttpResponse<String> response = client.send(upload, HttpResponse.BodyHandlers.ofString());
String echoed = response.body().substring(response.body().indexOf("body=") + 5);
System.out.println("Server received:\n" + echoed);
System.out.println("Timeout set: " + upload.timeout().orElseThrow().toSeconds() + " s");
} finally {
Files.delete(report);
server.stop(0);
}
}
}
Output:
Uploading 32 bytes
Server received:
month,amount
Jan,42000
Feb,51500
Timeout set: 10 s
How it works:
BodyPublishers.ofFile(report)reads the file while the request is being sent, so even large files do not need to fit in memory. It throwsFileNotFoundExceptionif the file does not exist.- The content length is known in advance (32 bytes), so Java sends a normal
Content-Lengthheader. timeout(Duration.ofSeconds(10))makessend()throwHttpTimeoutExceptionif the response takes longer, andupload.timeout()reads the value back.
Real-World Example: A REST API Client for Notes
Most Java HTTP requests in real projects call a REST API: create, read, update and delete resources (CRUD). This NotesClient wraps one shared HttpClient, adds the authentication header to every request, and offers one method per operation. The main method runs a full CRUD session against the /notes API of the local server.
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.time.Duration;
public class NotesClient implements AutoCloseable {
private final HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.build();
private final URI baseUri;
private final String token;
NotesClient(String baseUrl, String token) {
this.baseUri = URI.create(baseUrl.endsWith("/") ? baseUrl : baseUrl + "/");
this.token = token;
}
// Common settings for every request: URI, auth header, JSON, timeout
private HttpRequest.Builder request(String path) {
return HttpRequest.newBuilder(baseUri.resolve(path))
.header("Authorization", "Bearer " + token)
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(5));
}
private HttpResponse<String> send(HttpRequest request) throws IOException, InterruptedException {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.printf("%-6s %-9s -> %d %s%n", request.method(), request.uri().getPath(),
response.statusCode(), response.body());
return response;
}
HttpResponse<String> create(String json) throws IOException, InterruptedException {
return send(request("notes").header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(json)).build());
}
HttpResponse<String> list() throws IOException, InterruptedException {
return send(request("notes").GET().build());
}
HttpResponse<String> get(int id) throws IOException, InterruptedException {
return send(request("notes/" + id).GET().build());
}
HttpResponse<String> update(int id, String json) throws IOException, InterruptedException {
return send(request("notes/" + id).header("Content-Type", "application/json")
.PUT(BodyPublishers.ofString(json)).build());
}
HttpResponse<String> delete(int id) throws IOException, InterruptedException {
return send(request("notes/" + id).DELETE().build());
}
@Override
public void close() {
client.close();
}
public static void main(String[] args) throws Exception {
HttpServer server = ApiServer.start();
// 1. A wrong token is rejected with 401 Unauthorized
try (NotesClient guest = new NotesClient("http://localhost:8091", "wrong-token")) {
guest.list();
}
try (NotesClient notes = new NotesClient("http://localhost:8091", "demo-token")) {
// 2. Create two notes; the server returns 201 and a Location header
HttpResponse<String> created = notes.create("{\"title\":\"Buy milk\",\"done\":false}");
String location = created.headers().firstValue("Location").orElseThrow();
int firstId = Integer.parseInt(location.substring(location.lastIndexOf('/') + 1));
notes.create("{\"title\":\"Finish Java lesson\",\"done\":false}");
// 3. Read, update, delete
notes.list();
notes.update(firstId, "{\"title\":\"Buy milk\",\"done\":true}");
notes.get(firstId);
notes.delete(firstId);
// 4. The deleted note is gone
HttpResponse<String> missing = notes.get(firstId);
System.out.println("Note " + firstId + " still exists? " + (missing.statusCode() == 200));
} finally {
server.stop(0);
}
}
}
Output:
GET /notes -> 401 {"error":"missing or wrong token"}
POST /notes -> 201 {"id":1,"title":"Buy milk","done":false}
POST /notes -> 201 {"id":2,"title":"Finish Java lesson","done":false}
GET /notes -> 200 [{"id":1,"title":"Buy milk","done":false}, {"id":2,"title":"Finish Java lesson","done":false}]
PUT /notes/1 -> 200 {"id":1,"title":"Buy milk","done":true}
GET /notes/1 -> 200 {"id":1,"title":"Buy milk","done":true}
DELETE /notes/1 -> 204
GET /notes/1 -> 404 {"error":"note 1 not found"}
Note 1 still exists? false
How it works:
- One client, shared settings.
NotesClientcreates oneHttpClientwith a connect timeout. Its privaterequest(path)method returns a builder that already has the URI, theAuthorizationheader, theAcceptheader and a request timeout, so no request can forget them. - Safe URIs.
baseUri.resolve(path)joins the base address and the path. Making sure the base ends with/meansnotes/1is added under it, as explained in the Java URI class. - Authentication. The first client uses a wrong token, and the API answers
401. Checking the status code, not catching an exception, is how you detect this. - CRUD with the right methods.
createusesPOSTwith a JSON body,updateusesPUT,deleteusesDELETE, andlist/getuseGET. The server answers201 Createdwith aLocationheader for new notes, which the client reads to learn the new ID. - No-content responses. A successful
DELETEreturns204with an empty body, and a laterGETfor the same note returns404. - Cleaning up.
NotesClientimplementsAutoCloseableand closes itsHttpClient, so try-with-resources releases the connections.
To send these requests asynchronously, or to tune timeouts and redirects, combine this client with the techniques in the Java HttpClient lesson. For the networking basics underneath every HTTP request, see Java networking basics.