防止 HttpClient 4 遵循重定向

发布于 2024-08-02 21:09:52 字数 1539 浏览 1 评论 0原文

我正在使用 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
        }
    }
}

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

谢谢。

根据下面的解决方案,我在创建 DefaultHttpClient 客户端 之后(以及在将其传递给 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;
        }
    });
}

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

I'm connecting to my AppEngine application using the Apache HttpComponents library. In order to authenticate my users, I need to pass an authentication token along to the application's login address (http://myapp.appspot.com/_ah/login?auth=...) and grab a cookie from the header of the response. However, the login page responds with a redirect status code, and I don't know how to stop HttpClient from following the redirect, thus thwarting me from intercepting the cookie.

Fwiw, the actual method I use to send the request is below.

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
        }
    }
}

How would I stop the client from following the redirect?

Thanks.

Update:

As per the solution below, I did the following after creating a DefaultHttpClient client (and before passing it to the execute method):

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;
        }
    });
}

More verbose than it seems it needs to be, but not as difficult as I thought.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

-小熊_ 2024-08-09 21:09:52

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

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

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

HAN​​DLE_REDIRECTS

控制:

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

You can do it with the http params:

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

The method has no javadoc, but if you look at the source you can see it sets:

HANDLE_REDIRECTS

which controls:

Defines whether redirects should be handled automatically

生生漫 2024-08-09 21:09:52

对于 HttpClient 版本 4.3.x,它直接位于 clientBuilder

因此,当您构建客户端时,请使用:

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

我知道这是一个老问题,但我也遇到了这个问题,并且想分享我的解决方案。

With the Version 4.3.x of HttpClient its directly in the clientBuilder.

so when u build your Client use:

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

I know its an old question but I had this problem too and want to share my solution.

风铃鹿 2024-08-09 21:09:52

Try using a RedirectHandler. That may require extending DefaultHttpClient to return your custom implementation from createRedirectHandler().

没︽人懂的悲伤 2024-08-09 21:09:52

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 的特定实现联系起来,但它确实完成了这项工作。

The RedirectHandler seem to be deprecated, I managed to disable automatically following the redirect responses by changing the default RedirectionStrategy for the DefaultHttpClient liks this:

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;
        }
    });

On the downside, this tie us to a specific implementation of the HttpClient but it does the job.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文