Request Bodies and Headers
POST data and set headers.
Request Bodies and Headers is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Request Bodies and Headers
GET requests rarely need a body, but POST, PUT, and PATCH do. The JDK HTTP client uses BodyPublisher objects to supply request bodies and builder methods to set headers.
This lesson covers sending data and controlling headers like Content-Type.
BodyPublishers.ofString
The simplest publisher sends a string body. Pass it to the POST(...) method on the request builder.
BodyPublishers.noBody() exists for requests with no body.
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"Ada\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/users"))
.POST(BodyPublishers.ofString(json))
.build();
System.out.println("Method: " + request.method());
}
}Setting a Single Header
Use header(name, value) to add one header. To send JSON, you almost always set Content-Type.
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
public class Main {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/users"))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString("{}"))
.build();
System.out.println("Has Content-Type: " +
request.headers().firstValue("Content-Type").isPresent());
}
}Multiple Headers at Once
headers(name1, value1, name2, value2, ...) sets several headers in one call. The argument count must be even or it throws IllegalArgumentException.
import java.net.URI;
import java.net.http.HttpRequest;
public class Main {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.headers(
"Accept", "application/json",
"Accept-Language", "en-US")
.GET()
.build();
System.out.println(request.headers().map().keySet());
}
}Authorization Headers
Bearer tokens are sent via the Authorization header. Build the value as a string; never log the raw token.
public class Main {
public static void main(String[] args) {
String token = "abc123";
String headerValue = "Bearer " + token;
System.out.println("Authorization: Bearer ***");
System.out.println("Length: " + headerValue.length());
}
}PUT and DELETE
The builder has dedicated methods: PUT(publisher), DELETE(), and the generic method(name, publisher) for anything else such as PATCH.
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
public class Main {
public static void main(String[] args) {
HttpRequest patch = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/users/1"))
.method("PATCH", BodyPublishers.ofString("{\"active\":true}"))
.build();
System.out.println("Method: " + patch.method());
}
}Form-Encoded Bodies
For application/x-www-form-urlencoded data you build the body string manually, URL-encoding each value, then publish it as a string.
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
String body = "name=" + URLEncoder.encode("Ada Lovelace", StandardCharsets.UTF_8)
+ "&role=" + URLEncoder.encode("engineer", StandardCharsets.UTF_8);
System.out.println(body);
}
}Sending a File Body
BodyPublishers.ofFile(path) streams a file as the request body without loading it all into memory — ideal for uploads.
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/upload"))
.header("Content-Type", "application/octet-stream")
.POST(BodyPublishers.ofFile(Path.of("data.bin")))
.build();
System.out.println("Upload request built");
}
}Byte-Array Bodies
When you already have bytes in memory, BodyPublishers.ofByteArray(byte[]) sends them directly. Useful for binary payloads built at runtime.
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
byte[] payload = "raw-bytes".getBytes(StandardCharsets.UTF_8);
// BodyPublishers.ofByteArray(payload) would wrap these bytes
System.out.println("Payload size: " + payload.length + " bytes");
}
}Restricted Headers
For security, the client forbids you from setting certain headers such as Host, Content-Length, Connection, and Upgrade. Attempting to set them throws IllegalArgumentException — the client manages them itself.
Putting It Together
A typical JSON POST combines a body publisher and a content-type header:
.POST(BodyPublishers.ofString(json)).header("Content-Type", "application/json")- add
.header("Authorization", "Bearer ...")if needed
Quick Check
Test your understanding of request bodies and headers.
Recap
You learned to send data and control headers:
- BodyPublishers.ofString / ofByteArray / ofFile supply request bodies.
- POST / PUT / DELETE / method(...) choose the HTTP verb.
- header(...) and headers(...) set request headers.
- Set
Content-Typefor JSON and form data; useAuthorizationfor tokens. - Some headers (Host, Content-Length) are restricted and managed by the client.
Frequently asked questions
Is the “Request Bodies and Headers” lesson free?
Yes — the full text of “Request Bodies and Headers” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Request Bodies and Headers”?
POST data and set headers. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Request Bodies and Headers” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- java.net.http.HttpClient
- Async Requests
- Request Bodies and Headers
- Handling Responses