簡體   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