Michael
Michael

Reputation: 33297

How to get Response Body when Server responds with 302 in Grails?

I want to request server side an image from a different server with a GET request. If the requesting server response with status code 200 everything works fine. But often I get FOUND 302 redirect as status code. In this case there is no response.body which I need.

This is the code I use to retrieve a user image from facebook. Since facebook makes a redirect I get 302 as status code and not response.body.

def uri = new URI("http://graph.facebook.com/1000345345345/picture?width=200&height=200")
def requestFactory = new SimpleClientHttpRequestFactory()

def request = requestFactory.createRequest(uri, HttpMethod.GET)

try {
        def response = request.execute()
        def statusCode = response.statusCode
        if (statusCode == HttpStatus.FOUND) {
            log.debug "302" 
            // how do I get the response body?
        }

        if (statusCode == HttpStatus.OK) {
            return response.body.bytes
        }
        else if(statusCode == HttpStatus.FORBIDDEN) {
            throw new IllegalAccessError(response.statusCode.toString())
        }
} catch(ex) {
    log.error "Exception while querying $url", ex
}
return null

How do I get the correct response body in case on 302?

Upvotes: 3

Views: 1665

Answers (1)

user2980344
user2980344

Reputation:

You can use this. You method is:

def queryUrl(url, ...) {} 

You can use:

        if (statusCode == HttpStatus.FOUND) {
            def newUrl = response.connection.responses.getHeaders().Location[0]
            log.debug "302 redirect to ${newUrl}"
            return queryUrl(newUrl, "")
        }

This will request the redirected url.

Upvotes: 1

Related Questions