我正在使用 Gralis 1.3.7。我正在编写一个 Controller ,需要从另一台服务器获取 PDF 文件并将其返回给客户端。我想以某种相当有效的方式做到这一点,例如以下:
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();
}
}
我遇到的问题是弄清楚如何根据从源
返回的信息设置 Controller 响应的内容长度。我找不到有关 Grails 增强的 URL 类的文档。
最好的方法是什么?
基因
已编辑:修复了 setHeader 中的参数值
更新于 2012 年 3 月 16 日 10:49(太平洋标准时间)
更新于 2012 年 3 月 19 日 10:45(太平洋标准时间) 将后续问题移至单独的问题。
最佳答案
您可以使用 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();
}
}
关于http - 在 grails 中编写代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9730139/