Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download image using 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 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?

like image 346
gstackoverflow Avatar asked Aug 18 '15 18:08

gstackoverflow


People also ask

How do I download files from RestTemplate?

RestTemplate provides the following two ways to download a file from a remote Http url: Using byte array (holding everything in memory) Using ResponseExtractor (stream the response instead of loading it to memory)

How does rest template work?

According to the official documentation, RestTemplate is a synchronous client to perform HTTP requests. It is a higher-order API since it performs HTTP requests by using an HTTP client library like the JDK HttpURLConnection, Apache HttpClient, and others.

Where do we use REST template?

We can use RestTemplate to test HTTP based restful web services, it doesn't support HTTPS protocol. RestTemplate class provides overloaded methods for different HTTP methods, such as GET, POST, PUT, DELETE etc.


1 Answers

Image is a byte array, so you need to use byte[].class object as a second argument for 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);

To make it work, you will need to configure a ByteArrayHttpMessageConverter in your application config:

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

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    return new ByteArrayHttpMessageConverter();
}

I've tested this in a Spring Boot project and the image is saved to a file as expected.

like image 104
mzc Avatar answered Sep 22 '22 12:09

mzc