How to upload an image using the rest template?

I have the following code:

restTemplate.getForObject("http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg", File.class); 

I especially liked the image, which does not require authorization and is available to absolutely everyone.

when the following code is executed, I see the following stack:

 org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.io.File] and content type [image/jpeg] at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:559) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512) at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:243) at com.terminal.controller.CreateCompanyController.handleFileUpload(CreateCompanyController.java:615) 

what am I wrong

+5
source share
2 answers

The image is an array of bytes, so you need to use the byte[].class object as the second argument to RestTemplate.getForObject :

 String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg"; byte[] imageBytes = restTemplate.getForObject(url, byte[].class); Files.write(Paths.get("image.jpg"), imageBytes); 

For it to work, you need to configure ByteArrayHttpMessageConverter in the application configuration:

 @Bean public RestTemplate restTemplate(List<HttpMessageConverter<?>> messageConverters) { return new RestTemplate(messageConverters); } @Bean public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() { return new ByteArrayHttpMessageConverter(); } 

I tested this in a Spring boot project, and the image is saved in a file as expected.

+8
source

RestTemplate expects a class (for example, some view in memory) to convert the response from the server to. For example, it can transform an answer like:

 {id: 1, name: "someone"} 

into a class like:

 class NamedThing { private int id; private String name; // getters/setters go here } 

By calling:

 NamedThing thing = restTemplate.getForObject("/some/url", NamedThing.class); 

But it seems to you that you really want to make a response from the server and transfer it directly to the file. There are various methods to get the response body of your HTTP request as something like an InputStream , which you can read gradually and then OutputStream to an OutputStream (for example, your file).

This answer shows how to use IOUtils.copy() from commons-io to do the dirty work. But you need to get the InputStream of your file ... HttpURLConnection way is to use HttpURLConnection . There is a tutorial with more information.

+1
source

All Articles