In this article, you will learn how to make different kinds of HTTP POST requests by using the RestTemplate class in a Spring Boot application.

An HTTP POST request is used to create a new resource. The RestTemplate class provides several template methods like postForObject(), postForEntity(), and postForLocation() for making POST requests. The first two methods are very similar to what I have discussed before in RestTemplate's GET request tutorial. The last method returns the location of the newly created resource instead of returning the full resource.

Simple POST Request

To make a simple HTTP POST request using RestTemplate, you can use the postForEntity method and pass the request body parameters as a map object:

// request url
String url = "https://reqres.in/api/users";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// request body parameters
Map<String, String> map = new HashMap<>();
map.put("name", "John Doe");
map.put("job", "Java Developer");

// send POST request
ResponseEntity<Void> response = restTemplate.postForEntity(url, map, Void.class);

// check response
if (response.getStatusCode() == HttpStatus.OK) {
    System.out.println("Request Successful");
} else {
    System.out.println("Request Failed");
}

POST Request with JSON and Headers

To make a POST request with the JSON request body, we need to set the Content-Type request header to application/json. The following example demonstrates how to make an HTTP POST request with JSON request body:

// request url
String url = "https://jsonplaceholder.typicode.com/posts";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// create headers
HttpHeaders headers = new HttpHeaders();
// set `content-type` header
headers.setContentType(MediaType.APPLICATION_JSON);
// set `accept` header
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// request body parameters
Map<String, Object> map = new HashMap<>();
map.put("userId", 1);
map.put("title", "Spring Boot 101");
map.put("body", "A powerful tool for building web apps.");

// build the request
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(map, headers);

// send POST request
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

// check response
if (response.getStatusCode() == HttpStatus.CREATED) {
    System.out.println("Request Successful");
    System.out.println(response.getBody());
} else {
    System.out.println("Request Failed");
    System.out.println(response.getStatusCode());
}

POST Request with Basic Authentication

The following example demonstrates how to add basic authentication to RestTemplate POST request:

// request url
String url = "https://reqres.in/api/login";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// add basic authentication
headers.setBasicAuth("username", "password");

// build the request
HttpEntity request = new HttpEntity(headers);

// send POST request
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

// check response
if (response.getStatusCode() == HttpStatus.OK) {
    System.out.println("Login Successful");
} else {
    System.out.println("Login Failed");
}

POST Request with Response Mapped to Java Object

RestTemplate allows you to map the JSON response directly to a Java object. Let us first create a simple Post class:

public class Post implements Serializable {

    private int userId;
    private int id;
    private String title;
    private String body;

    public Post() {
    }

    public Post(int userId, int id, String title, String body) {
        this.userId = userId;
        this.id = id;
        this.title = title;
        this.body = body;
    }

    // getters and setters, equals(), toString() .... (omitted for brevity)
}

We can now use the above class to map the JSON response, as shown below:

// request url
String url = "https://jsonplaceholder.typicode.com/posts";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// create a post object
Post post = new Post(101, 1, "Spring Boot 101",
                "A powerful tool for building web apps.");

// build the request
HttpEntity<Post> request = new HttpEntity<>(post, headers);

// send POST request
ResponseEntity<Post> response = restTemplate.postForEntity(url, request, Post.class);

// check response
if (response.getStatusCode() == HttpStatus.CREATED) {
    System.out.println("Post Created");
    System.out.println(response.getBody());
} else {
    System.out.println("Request Failed");
    System.out.println(response.getStatusCode());
}

Check out the Making HTTP Requests using RestTemplate in Spring Boot guide for more RestTemplate examples.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.