RestTemplate does send null values in object

好久不见. 提交于 2019-12-11 15:53:19

问题


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("roger@example.com");
        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?


回答1:


@RequestBody missing for @PostMapping

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


来源:https://stackoverflow.com/questions/52915183/resttemplate-does-send-null-values-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!