Writing a proxy in grails

2019-07-15 17:41发布

问题:

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