0

I have a method that is configured to return either JSON or XML output using Spring boot 2.6.2. while it works fine for JSON, while trying to return XML output, it gives an exception - org.springframework.web.HttpMediaTypeNotAcceptableException

Provided below is the code example

    @PostMapping (
            produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
            consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<CreateUserResponseModel> createUser(@Valid @RequestBody CreateUserRequestModel userDetails) {

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        UserDTO userDTO = modelMapper.map(userDetails, UserDTO.class);
        UserDTO createdUser = userService.createUser(userDTO);

        CreateUserResponseModel returnValue = modelMapper.map(createdUser, CreateUserResponseModel.class);

        return ResponseEntity.status(HttpStatus.CREATED).body(returnValue);
    }

The following has been configured in the POM file

        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

Configuration in Postman to call a POST method is as follows; Headers:

1. Accept: application/XML
2. Content-Type: application/JSON

When I run this for Accept: application/JSON, it works fine. However, when the Accept parameter is changed to application/XML, it gives an exception org.springframework.web.HttpMediaTypeNotAcceptableException

Any suggestions on what needs to change in the annotation or code?

  • Where do you change the accept parameter? How do you send a request? What is the content of the request? – gerstams Jan 03 '22 at 09:04
  • The request is sent through the Postman app. Accept and Content-Type parameters are setup in the Header attributes of Postman – Hemant Satam Jan 04 '22 at 15:50

0 Answers0