Skip to content
Advertisement

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

This is my controller:

@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;
        
    }

This is the error I get:

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement