如何在Spring控制器中从URL服务器inputStream
我正在尝试构建一个 Spring 控制器来从 url 提供文件:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ResponseEntity<byte[]> getFile () throws IOException {
CommonHttpClient client = new CommonHttpClient();
URL url = new URL("http://www.google.com");
InputStream stream = url.openStream();
final HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html");
return new ResponseEntity<byte[]>(IOUtils.toByteArray(stream), headers, HttpStatus.CREATED);
}
我在 bean 配置中的 AnnotationMethodHandlerAdaptor 中有 ByteArrayHttpMessageConverter 。
但是,当我调用此页面时,我收到了无意义的字符串,例如 “PHBYzT5QB……” url 肯定可以访问并且没有抛出 IOException。 我在这里缺少什么?
I am trying to build a Spring controller to serve a file from a url:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ResponseEntity<byte[]> getFile () throws IOException {
CommonHttpClient client = new CommonHttpClient();
URL url = new URL("http://www.google.com");
InputStream stream = url.openStream();
final HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/html");
return new ResponseEntity<byte[]>(IOUtils.toByteArray(stream), headers, HttpStatus.CREATED);
}
I have ByteArrayHttpMessageConverter in my AnnotationMethodHandlerAdaptor in bean configuration.
However, when I call this page, I am getting nonsensical strings like
"PHBYzT5QB...."
The url is definitely reachable and no IOException were thrown.
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你在这里混合了一些东西。如果您想要提供的文件在本地文件系统上可用,那么您不需要从 URL 读取。如果您使用 HttpResponse 参数定义方法签名,您将能够获取 OutputStream 并写入它。不需要转换器 - 只需从一个流(文件)读取并循环写入另一个流(文件)即可。在响应中设置正确的内容类型标头也很重要。
I think you're mixing few things here. If the file you want to serve available on your local file system then you don't need to read from URL. If you define your method signature with HttpResponse parameter you will be able to get OutputStream and write to it. No converters should be necessary - just read from one stream (file) and write to the other in a loop. It is also important to set correct content type header in response.
我认为这是 BASE 编码的字节数组
i think this is BASE encoded byte array