http - 在 grails 中编写代理

标签 http grails character-encoding

我正在使用 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/

相关文章:

javascript - Lambda 未将 http 响应正文返回到 API 网关

asp.net - 路径 'PROPFIND' 被禁止?

java - 如何编写 Java 函数来返回 Unicode 点的标准名称?

Grails 数据绑定(bind) - 带有 Maps 的命令对象

Vim - 在重音字母或 ñ 之后插入额外的空格

java - java.nio.charset.Charset.decode(..)/encode(..) 的快速替代品

wcf - IFrame 回调,服务器响应未出现在客户端上

http - JMeter:如何发送带有内容类型 header 的请求?

mongodb - Grails GORM + Mongo,如何将自定义数据保存到ID?

grails - 包装内的服务