Sub topic 8
Sending a body with BodyPublishers
This chapter assumes you can build an HttpClient and an HttpRequest with a builder, and that you know what a request body and the Content-Type header are. It covers how to attach a body to a request.
What a BodyPublisher does
A BodyPublisher is an object that supplies the bytes of a request body. You do not write bytes to a socket yourself. You pass a publisher to the request builder, and the client pulls bytes from it while sending.
The factory class HttpRequest.BodyPublishers creates the common publishers. The builder methods that take one are POST(publisher), PUT(publisher), and the general method(name, publisher).
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/items"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"widget\"}"))
.build();A publisher never sets headers. You must set Content-Type yourself, because the client cannot infer it from a String or a byte array. A missing or wrong Content-Type is a common cause of 400 or 415 responses.
The built-in publishers
| Factory method | Source of bytes | Length known up front |
|---|---|---|
| `ofString(String)` | A string, encoded as UTF-8 | Yes |
| `ofString(String, Charset)` | A string in the charset you choose | Yes |
| `ofByteArray(byte[])` | An in-memory array | Yes |
| `ofByteArray(byte[], offset, length)` | Part of an array | Yes |
| `ofFile(Path)` | A file on disk, read as needed | Yes |
| `ofInputStream(Supplier)` | A stream created on demand | No |
| `noBody()` | Nothing | Yes (zero) |
"Length known" matters. When the publisher reports its length, the client sends a Content-Length header. When the length is unknown, as with ofInputStream, HTTP/1.1 uses chunked transfer encoding, and HTTP/2 simply streams the data. Some servers reject chunked uploads, so check the server's documentation before you stream from a stream.
Strings, charsets and form data
ofString(String) encodes with UTF-8. If the server expects another charset, pass it explicitly and declare it in Content-Type.
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 FormPost {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String form = "user=" + URLEncoder.encode("Ana Ruiz", StandardCharsets.UTF_8)
+ "¬e=" + URLEncoder.encode("caf\u00e9 & tea", StandardCharsets.UTF_8);
HttpRequest request = HttpRequest.newBuilder(URI.create("https://httpbin.org/post"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
}
}The client has no form builder. You encode each value with URLEncoder and join the pairs with &. Skipping the encoding breaks values that contain &, =, spaces or non-ASCII characters.
Byte arrays
Use ofByteArray for binary data you already hold in memory, such as a serialized message or an image.
byte[] payload = java.nio.file.Files.readAllBytes(java.nio.file.Path.of("small.png"));
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/images"))
.header("Content-Type", "image/png")
.POST(HttpRequest.BodyPublishers.ofByteArray(payload))
.build();The array is not copied when you create the publisher. If you change the array before the request is sent, the changed bytes go out. For a request you may reuse or send later, treat the array as read-only.
Files
ofFile streams a file from disk without loading it all into memory.
import java.nio.file.Path;
HttpRequest upload = HttpRequest.newBuilder(URI.create("https://api.example.com/upload"))
.header("Content-Type", "application/octet-stream")
.PUT(HttpRequest.BodyPublishers.ofFile(Path.of("report.pdf")))
.build();ofFile throws FileNotFoundException, a checked exception, at the moment you call it, not when the request is sent. Put that call inside your try block. This is a raw file upload. It is not a multipart/form-data request, which the API does not build for you.
Streams
ofInputStream takes a Supplier<? extends InputStream>, not a stream. The client calls the supplier each time it needs to read the body, which can happen more than once. A redirect that keeps the body, or your own retry loop that resends the same request, calls it again. Each call must return a fresh stream.
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
HttpRequest.BodyPublisher streamed = HttpRequest.BodyPublishers.ofInputStream(
() -> new ByteArrayInputStream("generated data".getBytes(StandardCharsets.UTF_8)));The client closes the stream it receives. Returning one shared stream from the supplier is a bug. The second use sees a closed or exhausted stream.
Requests with no body
GET() and DELETE() need no publisher. Some APIs require a POST or PUT with an empty body, such as a "trigger" endpoint. Use noBody():
HttpRequest trigger = HttpRequest.newBuilder(URI.create("https://api.example.com/jobs/7/run"))
.POST(HttpRequest.BodyPublishers.noBody())
.build();For a method without a dedicated builder call, such as PATCH, use method:
HttpRequest patch = HttpRequest.newBuilder(URI.create("https://api.example.com/items/3"))
.header("Content-Type", "application/json")
.method("PATCH", HttpRequest.BodyPublishers.ofString("{\"name\":\"gadget\"}"))
.build();Common errors
- No
Content-Type. The server cannot interpret the body. Set it on every request that has a body. - Setting
Content-Lengthyourself. The client treats it as a restricted header and throwsIllegalArgumentExceptionwhen you build the request. Let the publisher decide. - Wrong charset.
ofStringuses UTF-8 while the header says something else, or the reverse. - Reusing a stream in the supplier. See the streams section above.
- Large strings in memory.
ofStringandofByteArrayhold the whole body. For large uploads, preferofFileorofInputStream.
Exercise
A request built with BodyPublishers.ofInputStream(() -> sharedStream), where sharedStream is one InputStream created earlier, works the first time and sends an empty body when you send it again. Why, and how do you fix it?
Show answer
The client closes the stream it gets from the supplier after reading it, and the supplier returns the same, now exhausted, stream on the second call. Make the supplier create a new stream on every call, for example () -> new ByteArrayInputStream(bytes) or () -> Files.newInputStream(path). The latter throws IOException, so wrap it and rethrow as UncheckedIOException.
Exercise
You need to send POST with an empty body to /jobs/7/run. Which publisher do you use, and does the request need a Content-Type header?
Show answer
Use BodyPublishers.noBody(). No Content-Type is needed because there is no body, though a particular server may still document one.