Proxy request in grails controller

I was getting having issues with this for quite some time. The following code will was working on text pages without the closes, but wouldn’t proxy a map image layer without them.

Assuming you have a “targetUrl” that you are trying to proxy then the following code should work.

This code does use an internal “Request” and “HTTPClient” object that wraps the ones from Apache to make it easier to use. But in this case isn’t the difficult bit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def proxyRequest = new Request()
proxyRequest.httpMethod = "GET"
proxyRequest.keepStreamOpen = true
def fullURL = "${targetUrl}"
if(request.getQueryString()){
fullURL+="?${request.getQueryString()}"
}
proxyRequest.uri = new URI(fullURL)
proxyRequest.responseHandler = { HttpResponse proxyResponse ->
return proxyResponse
}
HttpResponse proxyResponse = httpClient.executeRequest(proxyRequest)
//This is the section that caused me issues.
int statusCode = proxyResponse.getStatusLine().getStatusCode()
response.status = statusCode
for(header in proxyResponse.getAllHeaders()){
response.setHeader(header.name, header.value)
}
response.outputStream << proxyResponse.getEntity().getContent()
// There is much documentation out there how this shouldn't be needed, but without these closes it
// wont return and there will be a content length mismatch.
proxyResponse.getEntity().getContent().close()
response.outputStream.flush()
response.outputStream.close()
return null
comments powered by Disqus