简体   繁体   中英

How to server inputStream from URL in Spring Controller

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?

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.

@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编码的字节数组

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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