AsconX
AsconX

Reputation: 171

RestTemplate does send null values in object

I have written a very simple EmailService using Spring boot.

A controller received an EmailRequest and sends the Mail:

@RestController
@Slf4j
public class EmailController {
    private final EmailService emailService;

    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @PostMapping
    public ResponseEntity sendEmail(EmailRequest request) {
        try {
            emailService.sendEmail(request);
        } catch (Exception e) {
            log.error("Error while sending email", e);
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok().build();
    }
}

I want to test the behaviour in another controller as follows:

@Controller
public class TestController {
    @GetMapping
    public ResponseEntity testSend(){
        EmailRequest request = new EmailRequest();
        request.setTo("[email protected]");
        request.setBody("This is the body");
        request.setSubject("This is a subject");
        return new RestTemplate().postForObject("http://localhost:9999",request,ResponseEntity.class);
    }
}

Now i set two breakpoints, one before sending the request via RestTemplate. As expected, the values are filled correctly.

Another breakpoint in the receiving controller is showing all values of EmailRequest null.

When I use PostMan to call the sending controller its working fine, so I probably doing something wrong with the RestTemplate.

Does anyone know what might be the problem?

Upvotes: 0

Views: 2133

Answers (1)

Barath
Barath

Reputation: 5283

@RequestBody missing for @PostMapping

@PostMapping
public ResponseEntity sendEmail(@RequestBody  EmailRequest request) { }

Upvotes: 1

Related Questions