RestTemplate POST Request with JSON and Headers

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 we discussed in RestTemplate's GET request tutorial. The last method returns the location of the newly created resource instead of the complete 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 a 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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.