Search code examples
javaspringpostinputstreamresttemplate

POST InputStream RestTemplate


I want to POST an InputStream to the Server. I'm using Spring and therefore RestTemplate to execute my HTTP Requests.

Client

    public void postSomething(InputStream inputStream) {
          String url = "localhost:8080/example/id";
          RestTemplate restTemplate = new RestTemplate();
          restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
          restTemplate.postForLocation(url, inputStream, InputStream.class); 
    }

Server

@PostMapping("/example/{id}")
public void uploadFile(@RequestBody InputStream inputStream, @PathVariable String id) { 
           InputStream inputStream1 = inputStream;
}

On Client side I get No HttpMessageConverter for [java.io.ByteArrayInputStream] And on Server side I get Cannot construct instance of 'java.io.InputStream' (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information


Solution

  • ByteArrayHttpMessageConverter is for byte[], not InputStream, just like the name of the class says.

    There are no built-in HttpMessageConverter for InputStream, but there is a ResourceHttpMessageConverter, which can handle e.g. an InputStreamResource.

    RestTemplate restTemplate = new RestTemplate(Arrays.asList(new ResourceHttpMessageConverter()));
    URI location = restTemplate.postForLocation(url, new InputStreamResource(inputStream));