by BehindJava

How to read XML or JSON payload from HTTP POST using consumes and @RequestBody in Spring Boot

Home » springboot » How to read XML or JSON payload from HTTP POST using consumes and @RequestBody in Spring Boot

In this tutorial we are going to learn about handling the HTTP POST request that sends a XML or JSON payload to the controller.

@RequestBody: Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

We have this method called create users and we added a post mapping annotation so that when HTTP post request is sent to the users this method can be invoked.

When the above payload is sent to the HTTP endpoint. It must be converted into a Java object. So that we can use within the Java method, and we must create a class that has getters and setters for the above JSON or XML payload within the application.

To enable the code reusability, I have used the same model class for setting and getting the values from Java object.

Sample Code Snippet:

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.behindjava.tutorial.model.UserModel;

@RestController
@RequestMapping("/users")
public class UserController {

	@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = {
			MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
	public ResponseEntity<UserModel> createUser(@RequestBody UserModel us) {

		UserModel um = new UserModel();
		um.setEmail(us.getEmail());
		um.setFirstname(us.getFirstname());
		um.setLastname(us.getLastname());
		um.setUserId(us.getUserId());

		return new ResponseEntity<UserModel>(um, HttpStatus.CREATED);
	}
}

In the post mapping we can specify the media type, consumes to enable the @PostMapping consume both XML and JSON.

title

When the post request is sent with the payload in the body of the HTTP POST request it returns the response as shown the above image.

Previous                                                                                                               Next