繁体   English   中英

如何在Spring Controller中从URL服务器inputStream

[英]How to server inputStream from URL in Spring Controller

我正在尝试构建一个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。 我在这里想念什么?

我想您在这里混了几件事。 如果要提供的文件在本地文件系统上可用,则无需从URL读取。 如果使用HttpResponse参数定义方法签名,则可以获取OutputStream并对其进行写入。 不需要转换器-只需从一个流(文件)中读取并在一个循环中写入另一个即可。 响应设置正确的内容类型标头也很重要。

@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);
  }
}

我认为这是BASE编码的字节数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM