【问题标题】:How to get Response Body when Server responds with 302 in Grails?当服务器在 Grails 中以 302 响应时如何获取响应正文?
【发布时间】:2014-04-06 20:37:02
【问题描述】:

我想通过 GET 请求向服务器端请求来自不同服务器的图像。如果请求服务器响应状态码为 200,则一切正常。 但我经常得到 FOUND 302 重定向作为状态码。在这种情况下,我不需要 response.body

这是我用来从 facebook 检索用户图像的代码。由于 facebook 进行重定向,我得到 302 作为状态码,而不是 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

如何在 302 上获得正确的响应正文?

【问题讨论】:

  • A 302 通常不包含响应正文。相反,您需要跟进请求并转到重定向的 URI。
  • @SotiriosDelimanolis 我认为 GET 上的请求将被自动重定向。不是这样吗?如何获取重定向URI?
  • 对不起,我不知道你的 Http 客户端。可能有一个设置可以让它通过。

标签: spring spring-mvc grails groovy


【解决方案1】:

你可以使用它。你的方法是:

def queryUrl(url, ...) {} 

你可以使用:

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

这将请求重定向的 url。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多