【问题标题】:Writing a proxy in grails在 grails 中编写代理
【发布时间】:2012-04-01 13:48:37
【问题描述】:

我使用的是 Gralis 1.3.7。我正在编写一个控制器,它需要从另一台服务器获取 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();
    }
}

我遇到的问题是如何根据从source 返回的信息来设置控制器响应的内容长度。我无法找到有关由 grails 增强的 URL 类的文档。

最好的方法是什么?

基因

已编辑:setHeader 中的固定参数值

更新于 2012 年 3 月 16 日太平洋标准时间 10:49

更新于 2012 年 3 月 19 日太平洋标准时间 10:45 将后续问题移至单独的问题。

【问题讨论】:

    标签: http grails character-encoding


    【解决方案1】:

    您可以使用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();
        }
    } 
    

    【讨论】:

    • 谢谢!这很接近——服务器响应一个看起来像 PDF 的流,浏览器认为它正在呈现 PDF,但我得到的只是空白页。会不会是发送了一些额外的信息,让 PDF 渲染器感到困惑?
    • 代码排序可行,但传输的文件与原始文件不同。这可能是字符编码问题吗?
    猜你喜欢
    • 2011-02-12
    • 2018-06-26
    • 2015-05-21
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    相关资源
    最近更新 更多