I have the following code:
restTemplate.getForObject("http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg", File.class);
I especially took image which doesn't require authorization and available absolutely for all.
when following code executes I see the following stacktrace:
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 do I wrong?
Image is a byte array, so you need to use
byte[].class
object as a second argument forRestTemplate.getForObject
:To make it work, you will need to configure a
ByteArrayHttpMessageConverter
in your application config:I've tested this in a Spring Boot project and the image is saved to a file as expected.
If you simply need to get an image from a URL, Java comes with the javax.imageio.ImageIO class, which contains this method signature:
example use:
The
RestTemplate
is expecting a class (e.g. some in-memory representation) to convert the response from the server into. For example, it could convert a response like:into a class like:
By calling:
But, what you seem to really want to do is to take the response from the server and stream it directly to a file. Various methods exist to get the response body of your HTTP request as something like an
InputStream
that you can read incrementally, and then write out to anOutputStream
(e.g. your file).This answer shows how to use
IOUtils.copy()
fromcommons-io
to do some the dirty work. But you need to get an InputStream of your file... A simple way is to use anHttpURLConnection
. There's a tutorial with more information.