我正在尝试构建一个 Spring Controller 来从 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。 我在这里缺少什么?
最佳答案
我认为你在这里混合了一些东西。如果您想要提供的文件在本地文件系统上可用,那么您不需要从 URL 读取。如果您使用 HttpResponse 参数定义方法签名,您将能够获取 OutputStream 并写入它。不需要转换器 - 只需从一个流(文件)读取并循环写入另一个流(文件)即可。在响应中设置正确的内容类型 header 也很重要。
@RequestMapping...
public void getFile(HttpResponse resp) throws IOException {
InputStream is = ... // get InputStream from your file
resp.setContentType("text/html"); // or whatever is appropriate for your file
OutputStream os = resp.getOutputStream();
// now read from one stream and write to the other
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
}
关于java - 如何在Spring Controller 中从URL服务器inputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9305264/