如何在春季从 Web 服务发送图像

2022-09-03 00:01:15

我在使用Spring Web服务发送图像时遇到问题。

我已经写了控制器如下

@Controller
public class WebService {

    @RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET)
    public @ResponseBody byte[] getImage() {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg");
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write( bufferedImage  , "jpg", byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

@ResponseBody将响应转换为 JSON。

我正在使用 RestClient 来测试 Web 服务。

但是当我用URL点击时。http://localhost:8080/my-war-name/rest/image

Header 
Accept=image/jpg

我在RestClient上遇到以下错误

使用 windows-1252 编码将响应正文转换为字符串失败。响应正文未设置!

当我使用浏览器Chrome和Firefox时

没有添加标题,所以错误是预期的(请指导我)

HTTP Status 405 - Request method 'GET' not supported

type Status report

message Request method 'GET' not supported

description The specified HTTP method is not allowed for the requested resource (Request method 'GET' not supported).

我也遇到过以下错误一次

此请求标识的资源只能根据请求“接受”标头生成具有不可接受的特征的响应 ()

我已经遵循了 http://krams915.blogspot.com/2011/02/spring-3-rest-web-service-provider-and.html 教程。

我的要求是将字节格式的图像发送到Android客户端。


答案 1

除了灵魂检查提供的答案。Spring为@RequestMapping注释添加了属性。因此,现在解决方案更容易:

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = "image/jpg")
public @ResponseBody byte[] getFile()  {
    try {
        // Retrieve image from the classpath.
        InputStream is = this.getClass().getResourceAsStream("/test.jpg"); 

        // Prepare buffered image.
        BufferedImage img = ImageIO.read(is);

        // Create a byte array output stream.
        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        // Write to output stream
        ImageIO.write(img, "jpg", bao);

        return bao.toByteArray();
    } catch (IOException e) {
        logger.error(e);
        throw new RuntimeException(e);
    }
}

答案 2

#soulcheck的答案部分是正确的。该配置在最新版本的Spring中不起作用,因为它会与元素冲突。请尝试以下配置。mvc-annotation

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
  </mvc:message-converters>
</mvc:annotation-driven>

一旦您在配置文件中具有上述配置。下面的代码将起作用:

@RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET)
public @ResponseBody BufferedImage getImage() {
    try {
        InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg");
        return ImageIO.read(inputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}