Reputation: 33297
I want to request an image from a url from within my Grails Service method. When I request the image from a url (in this case from Facebook) I get a 302 redirect. After that I request the new URL again. In the second response I get a 403 forbidden.
Here is the Service method that I use:
static queryImageUrl(url, query, MediaType contentType = urlencodedMediaType) {
if(query instanceof Map) {
query = map2query query
}
def uri = new URI("${url}?$query")
def requestFactory = new SimpleClientHttpRequestFactory()
def request = requestFactory.createRequest(uri, HttpMethod.GET)
try {
def response = request.execute()
def statusCode = response.statusCode
log.debug "got reply from $uri with status code $statusCode"
if (statusCode == HttpStatus.FOUND) {
def newUrl = response.connection.responses.getHeaders().Location[0]
log.debug "302 redirect to ${newUrl}"
return queryImageUrl(newUrl, "")
}
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 request an image from a url when the responds status is 302?
Edit:
Here are the logs from a image request for a Facebook user:
got reply from http://graph.facebook.com/10002342342395/picture?width=200&height=200 with status code 302
302 redirect to https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p200x200/10491179_578345345924700_6665003172531587407_n.jpg?oh=d91657acaf300c3d01042eccc22cf006&oe=543C6E19&__gda__=1415182364_3afb5be4b59d61c4bb2994d2605d2c65
got reply from https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p200x200/10491179_578563345345924700_666503453451587407_n.jpg?oh=d91657acaf300c3d01042eccc22cf006&oe=543C6E19&__gda__=1415182364_3afb5be4b59d61c4bb2994d2605d2c65? with status code 403
My recursive method is called a second time after the first response because of 302 and the second responds reports 403.
Upvotes: 1
Views: 548
Reputation: 20699
Had exactly the same problem recently. Then found out, that HTTPBuilder
handles redirects properly:
ByteArrayOutputStream baos = new ByteArrayOutputStream()
new HTTPBuilder( picUrl ).get( contentType:ContentType.BINARY ){ resp, reader ->
baos << reader
}
persistByteArraySomehow baos.toByteArray()
Update:
static queryImageUrl(url, query, MediaType contentType = urlencodedMediaType) {
if(query instanceof Map) {
query = map2query query
}
def uri = "${url}?$query"
ByteArrayOutputStream baos = new ByteArrayOutputStream()
try{
new HTTPBuilder( uri ).get( contentType:ContentType.BINARY ){ resp, reader ->
baos << reader
}
baos.toByteArray()
}finally{
baos.close()
}
}
Upvotes: 2