20

我正在使用 Apache HttpComponents 库连接到我的 AppEngine 应用程序。为了对我的用户进行身份验证,我需要将身份验证令牌传递给应用程序的登录地址(http://myapp.appspot.com/_ah/login?auth=.. .)并从标题中获取 cookie回复。但是,登录页面以重定向状态代码响应,我不知道如何阻止 HttpClient 跟随重定向,从而阻止我拦截 cookie。

Fwiw,我用来发送请求的实际方法如下。

private void execute(HttpClient client, HttpRequestBase method) {
    // Set up an error handler
    BasicHttpResponse errorResponse = new BasicHttpResponse(
            new ProtocolVersion("HTTP_ERROR", 1, 1), 500, "ERROR");

    try {
        // Call HttpClient execute
        client.execute(method, this.responseHandler);
    } catch (Exception e) {
        errorResponse.setReasonPhrase(e.getMessage());
        try {
            this.responseHandler.handleResponse(errorResponse);
        } catch (Exception ex) {
            // log and/or handle
        }
    }
}

我将如何阻止客户端遵循重定向?

谢谢。

更新

根据下面的解决方案,我在创建 a 之后DefaultHttpClient client(以及在将其传递给execute方法之前)执行了以下操作:

if (!this.followRedirect) {
    client.setRedirectHandler(new RedirectHandler() {
        public URI getLocationURI(HttpResponse response,
                HttpContext context) throws ProtocolException {
            return null;
        }

        public boolean isRedirectRequested(HttpResponse response,
                HttpContext context) {
            return false;
        }
    });
}

比它看起来需要的更冗长,但没有我想象的那么难。

4

5 回答 5

29

您可以使用 http 参数来做到这一点:

final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);

该方法没有 javadoc,但是如果您查看源代码,您可以看到它设置:

HANDLE_REDIRECTS

哪个控制:

定义是否应自动处理重定向

于 2009-11-09T05:09:37.937 回答
11

使用 HttpClient 的 4.3.x 版本,它直接在clientBuilder中。

所以当你建立你的客户时使用:

CloseableHttpClient client = clientBuilder.disableRedirectHandling().build();

我知道这是一个老问题,但我也有这个问题,想分享我的解决方案。

于 2014-08-27T06:44:23.880 回答
6

尝试使用RedirectHandler. 这可能需要扩展DefaultHttpClient以从createRedirectHandler().

于 2009-08-30T17:27:15.463 回答
1

RedirectHandler似乎已被弃用,我设法通过更改 DefaultHttpClient 的默认 RedirectionStrategy 来自动禁用重定向响应,如下所示:

httpClient.setRedirectStrategy(new RedirectStrategy() {
        @Override
        public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
            return false;
        }

        @Override
        public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException {
            return null;
        }
    });

不利的一面是,这将我们与 HttpClient 的特定实现联系在一起,但它确实可以完成工作。

于 2013-04-06T01:04:10.927 回答
0

一个快速的谷歌呈现:http ://hc.apache.org/httpclient-3.x/redirects.html

于 2009-08-30T08:50:55.867 回答