W3docs

POST request via RestTemplate in JSON

To make a POST request with the RestTemplate in JSON, you can use the postForObject() method and pass it the URL of the request, the request body, the response type, and the HttpEntity object that represents the request headers and body.

To make a POST request with the RestTemplate in JSON, you can use the postForEntity() method and pass it the URL of the request, the request body, the response type, and the HttpEntity object that represents the request headers and body.

Here is an example of making a POST request with the RestTemplate and a JSON request body:


import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

String url = "http://example.com/api/posts";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

Map<String, String> requestBody = new HashMap<>();
requestBody.put("title", "Hello World");
requestBody.put("content", "Lorem ipsum dolor sit amet");

HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

RestTemplate restTemplate = new RestTemplate();

ResponseEntity<Post> responseEntity = restTemplate.postForEntity(url, requestEntity, Post.class);
Post post = responseEntity.getBody();

In this example, the HttpHeaders class is used to create the request headers and set the Content-Type header to application/json. The HttpEntity class is used to create the request entity with the request body and the headers. The RestTemplate class is used to create a RestTemplate object and call the postForEntity() method to send the POST request. The ResponseEntity class is used to hold the response from the server, and the getBody() method is used to get the response body.

Note:

  • Ensure your project includes the spring-web (or spring-boot-starter-web) dependency.
  • JSON serialization relies on Jackson; include jackson-databind if it's not already on the classpath.
  • RestTemplate is deprecated in Spring 6.1+. For new projects, consider using RestClient or WebClient.
  • In production code, handle RestClientException and verify responseEntity.getStatusCode() for non-2xx responses.

I hope this helps. Let me know if you have any questions.