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.