The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Introduction
In this quick tutorial, we illustrate how to use Springβs RestTemplate to make POST requests sending JSON content.
Further reading:
Exploring the Spring Boot TestRestTemplate
Spring RestTemplate Error Handling
2. Setting Up the Example
Letβs start by adding a simple Person model class to represent the data to be posted:
public class Person {
private Integer id;
private String name;
// standard constructor, getters, setters
}
To work with Person objects, weβll add a PersonService interface and implementation with two methods:
public interface PersonService {
public Person saveUpdatePerson(Person person);
public Person findPersonById(Integer id);
}
The implementation of these methods will simply return an object. Weβre using a dummy implementation of this layer here so we can focus on the web layer.
3. REST API Setup
Letβs define a simple REST API for our Person class:
@PostMapping(
value = "/createPerson", consumes = "application/json", produces = "application/json")
public Person createPerson(@RequestBody Person person) {
return personService.saveUpdatePerson(person);
}
@PostMapping(
value = "/updatePerson", consumes = "application/json", produces = "application/json")
public Person updatePerson(@RequestBody Person person, HttpServletResponse response) {
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/findPerson/" + person.getId()).toUriString());
return personService.saveUpdatePerson(person);
}
Remember, we want to post the data in JSON format. In order to that, we added the consumes attribute in the @PostMapping annotation with the value of βapplication/jsonβ for both methods.
Similarly, we set the produces attribute to βapplication/jsonβ to tell Spring that we want the response body in JSON format.
We annotated the person parameter with the @RequestBody annotation for both methods. This will tell Spring that the person object will be bound to the body of the HTTP request.
Lastly, both methods return a Person object that will be bound to the response body. Letβs note that weβll annotate our API class with @RestController to annotate all API methods with a hidden @ResponseBody annotation.
4. Using RestTemplate
Now we can write a few unit tests to test our Person REST API. Here, weβll try to send POST requests to the Person API by using the POST methods provided by the RestTemplate: postForObject, postForEntity, and postForLocation.
Before we start to implement our unit tests, letβs define a setup method to initialize the objects that weβll use in all our unit test methods:
@BeforeClass
public static void runBeforeAllTestMethods() {
createPersonUrl = "http://localhost:8080/spring-rest/createPerson";
updatePersonUrl = "http://localhost:8080/spring-rest/updatePerson";
restTemplate = new RestTemplate();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
personJsonObject = new JSONObject();
personJsonObject.put("id", 1);
personJsonObject.put("name", "John");
}
Besides this setup method, note that weβll refer to the following mapper to convert the JSON String to a JSONNode object in our unit tests:
private final ObjectMapper objectMapper = new ObjectMapper();
As previously mentioned, we want to post the data in JSON format. To achieve this, weβll add a Content-Type header to our request with the APPLICATION_JSON media type.
Springβs HttpHeaders class provides different methods to access the headers. Here, we set the Content-Type header to application/json by calling the setContentType method. Weβll attach the headers object to our requests.
4.1. Posting JSON With postForObject
RestTemplateβs postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.
Letβs say that we want to make a POST request to our Person API to create a new Person object and return this newly created object in the response.
First, weβll build the request object of type HttpEntity based on the personJsonObject and the headers containing the Content-Type. This allows the postForObject method to send a JSON request body:
@Test
public void givenDataIsJson_whenDataIsPostedByPostForObject_thenResponseBodyIsNotNull()
throws IOException {
HttpEntity<String> request =
new HttpEntity<String>(personJsonObject.toString(), headers);
String personResultAsJsonStr =
restTemplate.postForObject(createPersonUrl, request, String.class);
JsonNode root = objectMapper.readTree(personResultAsJsonStr);
assertNotNull(personResultAsJsonStr);
assertNotNull(root);
assertNotNull(root.path("name").asText());
}
The postForObject() method returns the response body as a String type.
We can also return the response as a Person object by setting the responseType parameter:
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(person);
assertNotNull(person.getName());
Actually, our request handler method matching with the createPersonUrl URI produces the response body in JSON format.
But this is not a limitation for us β postForObject is able to automatically convert the response body into the requested Java type (e.g. String, Person) specified in the responseType parameter.
4.2. Posting JSON With postForEntity
Compared to postForObject(), postForEntity() returns the response as a ResponseEntity object. Other than that, both methods do the same job.
Letβs say that we want to make a POST request to our Person API to create a new Person object and return the response as a ResponseEntity.
We can make use of the postForEntity method to implement this:
@Test
public void givenDataIsJson_whenDataIsPostedByPostForEntity_thenResponseBodyIsNotNull()
throws IOException {
HttpEntity<String> request =
new HttpEntity<String>(personJsonObject.toString(), headers);
ResponseEntity<String> responseEntityStr = restTemplate.
postForEntity(createPersonUrl, request, String.class);
JsonNode root = objectMapper.readTree(responseEntityStr.getBody());
assertNotNull(responseEntityStr.getBody());
assertNotNull(root.path("name").asText());
}
Similar to the postForObject, postForEntity has the responseType parameter to convert the response body to the requested Java type.
Here, we were able to return the response body as a ResponseEntity<String>.
We can also return the response as a ResponseEntity<Person> object by setting the responseType parameter to Person.class:
ResponseEntity<Person> responseEntityPerson = restTemplate.
postForEntity(createPersonUrl, request, Person.class);
assertNotNull(responseEntityPerson.getBody());
assertNotNull(responseEntityPerson.getBody().getName());
4.3. Posting JSON With postForLocation
Similar to the postForObject and postForEntity methods, postForLocation also creates a new resource by posting the given object to the given URI. The only difference is that it returns the value of the Location header.
Remember, we already saw how to set the Location header of a response in our updatePerson REST API method above:
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/findPerson/" + person.getId()).toUriString());
Now letβs imagine that we want to return the Location header of the response after updating the person object we posted.
We can implement this by using the postForLocation method:
@Test
public void givenDataIsJson_whenDataIsPostedByPostForLocation_thenResponseBodyIsTheLocationHeader()
throws JsonProcessingException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
URI locationHeader = restTemplate.postForLocation(updatePersonUrl, request);
assertNotNull(locationHeader);
}
5. Handling Character Encoding in JSON POST Request
Spring Boot uses the server.servlet.encoding.charset property to configure the default encoding for the server. Moreover, it uses UTF-8 as the default value if the server.servlet.encoding.charset property is missing.
However, the server could misinterpret the incoming requests when the application uses a non-UTF-8 encoding, such as ISO-8859-1. In such scenarios, we must override the encoding by explicitly setting the Content-Type header. Letβs see how to do this using RestTemplate.
5.1. Simulating the Scenario
First, we must simulate the scenario by setting the server.servlet.encoding.charset property to ISO-8859-1 during the application startup:
SpringApplication app = new SpringApplication(RestTemplateApplication.class);
app.setDefaultProperties(
Collections.singletonMap("server.servlet.encoding.charset", "ISO-8859-1"));
app.run(args);
Now, letβs create an instance of the Person class with Japanese characters in the name:
Person japanese = new Person(100, "ι’ι£ε½");
Moving on, letβs create the request object with an instance of HttpHeaders:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Person> request = new HttpEntity<>(japanese, headers);
Next, letβs use an instance of RestTemplate to make a POST request to the createPersonUrl endpoint:
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
Lastly, letβs verify that the resultant person object doesnβt have the same name as we used in the request:
assertNotNull(person);
assertNotEquals("ι’ι£ε½", person.getName());
This issue occurred because Japanese characters arenβt handled by the ISO-8859-1 encoding, which our application uses.
5.2. Handling Character Encoding
We can handle the character encoding for the incoming request by setting the Content-type header to specify the UTF-8 encoding:
HttpHeaders headers = new HttpHeaders();
headers.set("Content-type", "application/json;charset=UTF-8");
HttpEntity<Person> request = new HttpEntity<>(japanese, headers);
Now, letβs go ahead and use restTemplate to make a POST request to the createPersonUrl endpoint:
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
Lastly, we can verify that the resultant person has the same name as expected:
assertNotNull(person);
assertEquals("ι’ι£ε½", person.getName());
It looks like weβve got this one right!
6. Conclusion
In this article, we explored how to use RestTemplate to make a POST request with JSON. Additionally, we also learned how to handle character encoding while making the POST requests.
