Java › Java Networking & HTTP Client
How would you send a POST request with a JSON request body using HttpClient, and correctly parse a JSON response using a library like Jackson?
IntermediateAnswer
HttpRequest.BodyPublishers.ofString(jsonString) constructs the request body, combined with setting the appropriate Content-Type: application/json header, sends a JSON payload; on the response side, HttpResponse.BodyHandlers.ofString() retrieves the raw JSON response body as a String, which you then deserialize into a Java object using a JSON library like Jackson's ObjectMapper, since HttpClient itself has no built-in JSON serialization/deserialization capability -- it deliberately operates purely at the HTTP transport level, leaving content-format handling to a separate, dedicated library.
ObjectMapper mapper = new ObjectMapper();
String jsonBody = mapper.writeValueAsString(new CreateUserRequest("Alice", "alice@example.com"));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
User createdUser = mapper.readValue(response.body(), User.class);Real-world example A client library calling a REST API serializes a Java DTO to JSON via Jackson before constructing the HttpRequest's body, then deserializes the JSON response back into a typed Java object after receiving it, cleanly separating HttpClient's pure HTTP transport responsibilities from Jackson's dedicated JSON serialization responsibilities.