Reputation: 1528
Java (tested on JDK11 and JDK17) HttpClient POST request with a "hello" body delivers empty body to the server.
val response = java.net.http.HttpClient.newHttpClient()
.send(
java.net.http.HttpRequest.newBuilder()
.uri(URI.create("http://...."))
.POST(java.net.http.HttpRequest.BodyPublishers.ofString("hello", StandardCharsets.UTF_8))
.build(),
java.net.http.HttpResponse.BodyHandlers.ofString());
No exception throw, response.statusCode()
is 202, the content-length
header shows 5
, but the request body is empty. Tested against multiple server implementations and Postman mock server.
I am executing this code from within a JUnit test.
OpenJDK 64-Bit Server VM Temurin-17.0.5+8 (build 17.0.5+8, mixed mode, sharing)
Update 2023-02-05
Debugging into the JVM, I see two buffers are queued for posting. One contains 9 characters (encoded message start frame?) and the second contains my 5 characters 104, 101, 108, 108, 111 (i.e. hello
).
The body publisher then seems to only send the first 9 characters and never my actual 5 character payload. Log follows (please pardon the length):
Upvotes: 0
Views: 1677
Reputation: 1528
Per @tevemadar's suggestion, setting a content type (Postman) makes the HttpClient push the data, (or the server to pull the data).
Adding .header("Content-Type", "text/plain")
helped made the body appear on the other side. Full code:
var response =
java.net.http.HttpClient.newHttpClient()
.send(
java.net.http.HttpRequest.newBuilder()
.uri(URI.create(uri))
.header("Content-Type", "text/plain")
.POST(
java.net.http.HttpRequest.BodyPublishers.ofString(
"hello", StandardCharsets.UTF_8))
.build(),
java.net.http.HttpResponse.BodyHandlers.ofString());
Not setting any content-type on the HttpRequest
makes the HttpClient::send
method call (or the server-side) ignore the request body (or perceive it as an empty body). There is no error, no warning, nothing in the JDK debug logs.
Setting any (even wrong) content type makes the body come across to the server side.
Upvotes: 2