2012-03-16 21 views
2

我正在使用Gralis 1.3.7。我正在編寫一個控制器,需要從另一臺服務器獲取PDF文件並將其返回給客戶端。我想做到這一點在一些合理有效的方式,如下面的:在grails中寫代理

class DocController { 
    def view = { 
     URL source = new URL("http://server.com?docid=${params.docid}"); 

     response.contentType = 'application/pdf'; 
     // Something like this to set the content length 
     response.setHeader("Content-Length", source.contentLength.toString()); 
     response << source.openStream(); 
    } 
} 

我有是搞清楚如何基於回來的信息設定我的控制器的響應的內容長度的問題來自source。我無法在URL類中找到grails增強的文檔。

什麼是繼續進行的最佳方式?

基因

編輯:在固定的setHeader參數值

已更新2012年3月16日10時49分PST

已更新2012年3月19日10點45 PST 搬遷後續工作一個單獨的問題。

回答

2

您可以使用java.net.URLConnection對象,它允許您使用URL做更詳細的工作。

URLConnection connection = new URL(url).openConnection() 

def url = new URL("http://www.aboutgroovy.com") 
def connection = url.openConnection() 
println connection.responseCode  // ===> 200 
println connection.responseMessage  // ===> OK 
println connection.contentLength  // ===> 4216 
println connection.contentType   // ===> text/html 
println connection.date    // ===> 1191250061000 
println connection.lastModified 

// print headers 
connection.headerFields.each{println it} 

你的榜樣應該看起來是這樣的:

class DocController { 
    def view = { 
     URL source = new URL("http://server.com?docid=${params.docid}"); 
     URLConnection connection = source.openConnection(); 

     response.contentType = 'application/pdf'; 

     // Set the content length 
     response.setHeader("Content-Length", connection.contentLength.toString()); 

     // Get the input stream from the connection 
     response.outputStream << connection.getInputStream(); 
    } 
} 
+0

謝謝!這很接近 - 服務器以PDF格式的流進行響應,瀏覽器認爲它正在渲染PDF,但我得到的只是空白頁面。難道是一些額外的信息正在發送混淆PDF渲染器? – 2012-03-16 03:38:01

+0

作品的代碼排序,但傳輸的文件與原始文件不同。這可能是一個字符編碼問題? – 2012-03-16 17:07:32

+0

我編輯了答案。技巧是在最後一行 – pablomolnar 2012-03-21 01:23:36