如何使用rest模板下载图像?

gst*_*low 9 java spring get http resttemplate

我有以下代码:

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

我特别拍摄了不需要授权的图片,绝对适用于所有人.

下面的代码执行时,我看到以下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)
Run Code Online (Sandbox Code Playgroud)

我错了什么?

mzc*_*mzc 16

Image是一个字节数组,因此您需要使用byte[].classobject作为第二个参数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);
Run Code Online (Sandbox Code Playgroud)

要使其工作,您需要ByteArrayHttpMessageConverter在应用程序配置中配置a :

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

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    return new ByteArrayHttpMessageConverter();
}
Run Code Online (Sandbox Code Playgroud)

我在Spring Boot项目中对此进行了测试,并将图像保存到文件中.


man*_*ni0 6

如果您只需要从 URL 获取图像,Java 附带了 javax.imageio.ImageIO 类,其中包含以下方法签名:

   public static BufferedImage read(URL var0) throws IOException;
Run Code Online (Sandbox Code Playgroud)

使用示例:

    try {
      BufferedImage image = ImageIO.read(new URL("http://www.foo.com/icon.png"));
      int height = image.getHeight();
      int width = image.getWidth();
    } catch (IOException e) {}
Run Code Online (Sandbox Code Playgroud)


pio*_*oto 0

期望RestTemplate一个类(例如一些内存中的表示)将来自服务器的响应转换为。例如,它可以转换如下响应:

{id: 1, name: "someone"}
Run Code Online (Sandbox Code Playgroud)

进入一个类,如:

class NamedThing {
    private int id;
    private String name;

    // getters/setters go here
}
Run Code Online (Sandbox Code Playgroud)

通过致电:

NamedThing thing = restTemplate.getForObject("/some/url", NamedThing.class);
Run Code Online (Sandbox Code Playgroud)

但是,您似乎真正想做的是从服务器获取响应并将其直接流式传输到文件。存在多种方法来获取 HTTP 请求的响应正文,例如InputStream您可以增量读取的内容,然后写入到OutputStream(例如您的文件)。

这个答案展示了如何使用IOUtils.copy()fromcommons-io来做一些肮脏的工作。但是您需要获取文件的 InputStream...一个简单的方法是使用HttpURLConnection. 有一个包含更多信息的教程