java - 如何在 Spring 中从 Web 服务发送图像

标签 java json spring spring-mvc

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

我写的 Controller 如下

@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 Service。

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

Header 
Accept=image/jpg

我在 RestClient 上遇到以下错误

Response body conversion to string using windows-1252 encoding failed. Response body not set!

当我使用 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).

我也遇到过一次以下错误

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()

我关注了 http://krams915.blogspot.com/2011/02/spring-3-rest-web-service-provider-and.html教程。

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

最佳答案

除了灵魂检查提供的答案。 Spring 已将 produces 属性添加到 @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);
    }
}

关于java - 如何在 Spring 中从 Web 服务发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8656085/

相关文章:

java - 如何将一种 JSON 模式映射到另一种模式?

spring boot 应用程序 - 从静态上下文中获取 bean

java - 在 spring boot @activeprofile 注解中配置 maven 配置文件

java - 我想在java中将字符串转换为日期

json - 使用 jq 解析 AWS CLI 工具的 json 输出

json - 使用组合器自定义 Json 写入 - 不需要 case 类的所有字段

java - 我怎样才能使spring.xml的xsi :schemaLocation work when my app is offline (finished product is an offline artifact)

java - Spring MVC 表单 - 引用对象的模型

java - writeUTF 和 writeChars 有什么区别?

java - 包括 WEKS、MONTHS、YEARS 的枚举