防止HttpClient 4跟随重定向

mju*_*ewu 20 google-app-engine android apache-commons

我正在使用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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何阻止客户端跟踪重定向?

谢谢.

更新:

根据下面的解决方案,我在创建一个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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

比看起来需要的更冗长,但并不像我想象的那么困难.

小智 29

您可以使用http参数执行此操作:

final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);
Run Code Online (Sandbox Code Playgroud)

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

HANDLE_REDIRECTS

控制:

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


Kre*_*ube 11

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

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

CloseableHttpClient client = clientBuilder.disableRedirectHandling().build();
Run Code Online (Sandbox Code Playgroud)

我知道这是一个古老的问题,但我也有这个问题,并希望分享我的解决方案.


Com*_*are 6

尝试使用RedirectHandler.这可能需要扩展DefaultHttpClient以返回您的自定义实现createRedirectHandler().