Request Bodies¶
Contents | Previous: Making Requests | Next: Handling Responses
View in another language — C++ · C#/.NET · Java · Kotlin · Node/TypeScript
After reading this chapter
You can send JSON as the usual request body and select the appropriate body form when an API requires form or multipart data.
A request body is attached to a request that sends content, such as POST, PUT, or PATCH. The HTTP client uses a typed JSON body as the default path for serializing an application DTO.
1. Send a JSON Body¶
A typed JSON body sends an application DTO as application/json. The response form is independent of the body format, so choose a typed response, raw response, or a body-only response as needed.
RawHttpResponse player =
client.post("/players/p2")
.body(new CreatePlayer("rookie"))
.submitRaw()
.toCompletableFuture()
.join();
RawHttpResponse room =
client.post("/rooms")
.body(new OpenRoom("lobby"))
.submitRaw()
.toCompletableFuture()
.join();
String roomId = stringBody(room);
RawHttpResponse chat =
client.post("/rooms/" + roomId + "/chat")
.body(new PostChat("p2", "hello"))
.submitRaw()
.toCompletableFuture()
.join();
System.out.println(
"json body: player "
+ player.status()
+ " room "
+ roomId
+ " chat "
+ chat.status());
// roomId is reused by the response, compression, download, and upload steps below.
2. Choose Form or Multipart¶
A form suits an API that accepts short name and value pairs as application/x-www-form-urlencoded. Multipart is multipart/form-data for sending text fields and file fields in one request. Form fields accumulate, and multipart fields and files accumulate into one body.
Choose one body source
Mixing typed JSON, raw content, a stream, a form, or multipart in one request ends with
protocolError before the request is sent.
3. Boundary for Raw and Streaming Bodies¶
A raw body with an arbitrary content type and a streaming upload that supplies byte chunks are separate paths from JSON, form, and multipart. Response Rules covers raw-body response handling, and Streaming covers streaming uploads.
Next Chapter¶
Handling Responses chooses a JSON-decoded response, a raw response, or a body-only response.