Sub topic 7
Sending a body with BodyPublishers
This chapter assumes you know Java 11 syntax, basic HTTP methods and headers, and checked exceptions. You will use HttpClient, HttpRequest, and HttpResponse from java.net.http.
An HTTP request body carries data from the client to the server. You usually send a body with methods such as POST, PUT, or PATCH. A BodyPublisher supplies those bytes to the request. The HttpRequest.BodyPublishers class provides factory methods for common sources.
Choosing a BodyPublisher
| Publisher | Use it for |
|---|---|
| `ofString` | Text, JSON, XML, or form data |
| `ofByteArray` | Data already held as bytes |
| `ofFile` | A file that should be read when the request is sent |
| `noBody` | Methods that do not need a body |
The publisher does not describe the data format. The Content-Type header does that. For example, a JSON string should usually use application/json.
Sending text or JSON
The following program sends a JSON object in a POST request. BodyPublishers.ofString converts the string into request data using UTF-8 by default.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class SendJson {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
String json = "{\"name\":\"widget\",\"quantity\":3}";
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://httpbin.org/post"))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = client.send(
request,
HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println(response.body());
}
}POST accepts a BodyPublisher, so the request builder knows that it has content to send. The server uses Content-Type to decide how to interpret that content. Accept tells the server which response format the client prefers.
The HttpClient API does not include a JSON encoder or decoder. For real applications, create JSON with a library such as Jackson rather than assembling strings manually. Manual construction becomes unsafe when values contain quotes, newlines, or other characters that require escaping.
Files and bytes
Use ofByteArray when the complete data is already in memory:
byte[] data = "hello".getBytes(java.nio.charset.StandardCharsets.UTF_8);
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/upload"))
.header("Content-Type", "text/plain; charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofByteArray(data))
.build();Use ofFile(Path) when the body comes from a file. This avoids first building a large byte array yourself. For very large uploads, consider the file size and failure behavior before sending.
Exercise
Which publisher should you choose for a JSON string, and which header should describe its format?
Show answer
Use BodyPublishers.ofString(json) and set Content-Type to application/json.