2012-02-16 86 views
0

我想建立一個Spring控制器爲來自URL的文件:如何從服務器URL的inputStream春季控制器

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

我有ByteArrayHttpMessageConverter在我的bean配置AnnotationMethodHandlerAdaptor。

然而,當我把這個頁面,我得到無意義的字符串像 「PHBYzT5QB ......」 的網址是絕對訪問,並沒有IOException異常被拋出。 我在這裏錯過了什麼?

回答

1

我覺得你在這裏混幾件事情。如果你想在本地文件系統上提供的文件可用,那麼你不需要從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); 
    } 
} 
+0

感謝您的回答。對不起,任何混淆,該文件確實是一個服務器。我會用www.google.com替換它以清楚說明。 IOUtils.toByteArray和你的代碼完全一樣,我也設置了內容類型。 – ltfishie 2012-02-16 04:09:24

+0

哇,我應該保持基本。使用HttpResponse確實有效。我會在稍後給你答案,但我想看看如何使用ResponseEntity 來完成這項工作,因爲它在我閱讀過的很多來源中都有提及。 – ltfishie 2012-02-16 04:30:06

+0

即使ResponseEntity的方法有效,我認爲它會比使用流更差,因爲整個文件需要同時保存在內存中,這對於大文件或更重要的請求速率來說是不可取的或不可能的 – maximdim 2012-02-16 12:07:06

0

我認爲這是BASE編碼的字節數組