Sending a JSON document via HTTP POST with plain Java 📎
In the following screencast:
...I posted a JSON document:
var message = """
{"message":"hello,duke"}
""";
...using a plain Java HttpClient:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
var client = HttpClient.newHttpClient();
...to the following URI:
var uri = new URI("http://localhost:8080/crud/");
...and an application/json
POST HTTP request.
var request = HttpRequest.newBuilder(uri).
POST(BodyPublishers.ofString(message))
.header("Content-type", "application/json").
build();
The HTTP status code and the headers are available from the HttpResponse:
var response = client.send(request, BodyHandlers.discarding());
assertEquals(201, response.statusCode());
var locationHeader = response.headers().firstValue("Location").get();
System.out.println(locationHeader);
//output: http://localhost:8080/crud/1620925145168
The "mockend" used in the screencast is available from: github.com/adambien/mockend