Writing a proxy in grails

你。 提交于 2020-01-04 09:15:32

问题


I am using Gralis 1.3.7. I am writing a controller that needs to get a PDF file from another server and return it to the client. I would like to do this in some reasonably efficient manner, such as the following:

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

The problem I am having is figuring out how to set the content length of the response of my controller based on the information coming back from source. I wasn't able to find the documentation on the URL class as enhanced by grails.

What's the best way to proceed?

Gene

EDITED: Fixed parameter values in setHeader

UPDATED 16 mar 2012 10:49 PST

UPDATED 19 March 2012 10:45 PST Moved follow-up to a separate question.


回答1:


You can use java.net.URLConnection object that will allow you to do a bit more detailed work with the 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}

Your example should looks something like this:

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


来源:https://stackoverflow.com/questions/9730139/writing-a-proxy-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!