I/O error while reading input message; nested exception is java.io.IOException: Stream closed

依然范特西╮ 提交于 2020-02-03 09:59:35

问题


@RestController
@RequestMapping("/reclamacao")
public class ClaimController {

    @Autowired
    private ClaimRepository claimRepository;

    @CrossOrigin
    @PostMapping("/adicionar")
    public Claim toCreateClaim(@Valid @RequestBody Claim claim, @RequestBody List<Sector> sectors) {

        if (claim.getNumber() != null) {
            if (claimRepository.findByNumber(claim.getNumber()).isPresent()) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Já existe uma reclamação com esse número.");
            }
        }

        claimRepository.save(claim);
        for (Sector sect: sectors) {
        claimRepository.saveClaim(claim.getId(), sect);
        }

        return claim;

    }

acima esta meu controller de uma claim que estou adicionando.

logo que executo a requisicao no postman ele devolve esse erro:

"message": "I/O error while reading input message; nested exception is java.io.IOException: Stream closed"


回答1:


Your error is the result of @RequestBody being used twice in your controller method arguments. Following line causes the issue:

toCreateClaim(@Valid @RequestBody Claim claim, @RequestBody List<Sector> sectors)

You cannot use it this way as only one @RequestBody per method is allowed. Using @RequestBody Spring converts incoming request body into the specified object (what closes the stream representing body at the end) so attempting to use @RequestBody second time in the same method makes no sense as stream has been already closed.

So in order to solve your issue, please create a dedicated object with both objects which you specified. Like:

public class Complaint {
  Claim claim;
  List<Sector> sectors;
}

And then change method arguments to:

toCreateClaim(@RequestBody Complaint complaint)

What is more, if you want to validate the structure of your object using @Valid and make the result accessible, you need to add BindingResult just after the argument which is validated:

toCreateClaim(@Valid @RequestBody Complaint complaint, BindingResult bindingResult)


来源:https://stackoverflow.com/questions/55051290/i-o-error-while-reading-input-message-nested-exception-is-java-io-ioexception

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