我在使用 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/