简体   繁体   English

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

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

I am trying to build a Spring controller to serve a file from a url: 我正在尝试构建一个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);
}

I have ByteArrayHttpMessageConverter in my AnnotationMethodHandlerAdaptor in bean configuration. 我在Bean配置中的AnnotationMethodHandlerAdaptor中具有ByteArrayHttpMessageConverter。

However, when I call this page, I am getting nonsensical strings like "PHBYzT5QB...." The url is definitely reachable and no IOException were thrown. 但是,当我调用此页面时,我得到了诸如“ PHBYzT5QB ....”之类的荒谬字符串,该URL绝对是可访问的,并且未引发IOException。 What am I missing here? 我在这里想念什么?

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. 如果要提供的文件在本地文件系统上可用,则无需从URL读取。 If you define your method signature with HttpResponse parameter you will be able to get OutputStream and write to it. 如果使用HttpResponse参数定义方法签名,则可以获取OutputStream并对其进行写入。 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. 响应设置正确的内容类型标头也很重要。

@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