Java 当响应为302时,如何从URL请求图像?
我想从Grails服务方法中的url请求一个图像。当我从url(本例中是从Facebook)请求图像时,我得到一个302重定向。之后,我再次请求新的URL。在第二个回答中,我得到一个403禁止 以下是我使用的服务方法:Java 当响应为302时,如何从URL请求图像?,java,spring,spring-mvc,grails,groovy,Java,Spring,Spring Mvc,Grails,Groovy,我想从Grails服务方法中的url请求一个图像。当我从url(本例中是从Facebook)请求图像时,我得到一个302重定向。之后,我再次请求新的URL。在第二个回答中,我得到一个403禁止 以下是我使用的服务方法: static queryImageUrl(url, query, MediaType contentType = urlencodedMediaType) { if(query instanceof Map) {
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
}
当响应状态为302时,如何从url请求图像?
编辑:
以下是Facebook用户的图像请求日志:
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
我的递归方法在第一次响应后第二次被调用,因为302和第二次响应报告403。最近遇到了完全相同的问题。然后发现
HTTPBuilder
正确处理重定向:
ByteArrayOutputStream baos = new ByteArrayOutputStream()
new HTTPBuilder( picUrl ).get( contentType:ContentType.BINARY ){ resp, reader ->
baos << reader
}
persistByteArraySomehow baos.toByteArray()
ByteArrayOutputStream=new ByteArrayOutputStream()
新的HTTPBuilder(picUrl).get(contentType:contentType.BINARY){resp,reader->
宝钢
baos您向302的响应位置
标题中的URL发送一个新请求。如果需要身份验证,您可以进行身份验证。您可以发布我如何修改我的示例吗?请参阅maven depcompile'org.codehaus.groovy.modules.http builder:http builder:0.7'
非常好的回答!谢谢!
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()
}
}