【问题标题】:Apache HttpClient 4.5 cross host redirectApache HttpClient 4.5 跨主机重定向
【发布时间】:2016-03-06 03:23:17
【问题描述】:

这是我的场景

我正在调用来自 HOSTA 的 url http://www.hosta.com/something

这会将我重定向到 HOSTB 网址 http://www.hostb.com/something

这是我从 url a 获得的响应代码

http-outgoing-5

http-outgoing-5

重定向到 www.hostb.com/something

http-outgoing-10 >> 主机:hosta.com

在最后一行中,我看到主机标头设置为 HOSTA,这是错误的。

这是我正在使用的代码

这就是创建连接的方式

private PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
HttpClientBuilder builder= HttpClients.custom();

builder.setMaxConnPerRoute(50)
    .setConnectionManager(cm)
    .setConnectionTimeToLive(timeout, TimeUnit.MILLISECONDS)
    .setDefaultCookieStore(cookieStore)
    .setRedirectStrategy(new LaxRedirectStrategy())
    .setDefaultSocketConfig(socketConfig)
    .setServiceUnavailableRetryStrategy(retryStrategy)
    .setKeepAliveStrategy(keepAliveStrategy)
    .setRetryHandler(myRetryHandler);

调用请求的方法

HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Cache-Control", "max-age=0");
post.setHeader("Connection", "keep-alive");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Upgrade-Insecure-Requests", "1");
post.setConfig(requestConfig);
if (origin != null) {
    post.setHeader("Origin", origin);
}
if (host != null) {
    post.setHeader("Host", host);
}
if (referer != null) {
    post.setHeader("Referer", referer);
}
//some more code

我正在使用运行良好的自动重定向(使用 LaxDirectStrategy)。但在这种特殊情况下,我遇到了问题。

在跨主机重定向的情况下,是否有任何方法可以更新 HOST 标头,或者可以为一个特定请求停止自动重定向?

【问题讨论】:

标签: apache-httpclient-4.x http-redirect


【解决方案1】:

我使用 RequestConfig 来禁用/启用特定请求的重定向。

默认情况下,我启用了重定向。每当我想禁用它时,我都会使用

RequestConfig requestConfig = RequestConfig.custom()
            .setRedirectsEnabled(false).build();//disable redirect
HttpPost post = new HttpPost(url);

post.setConfig(requestConfig);//poass the request config to request

【讨论】:

    【解决方案2】:

    我在使用 HttpClient 4.5.9(和 4.5.13)时也遇到了类似的问题。原来是我无意中写了Host这个标头。

    HttpClient 保留 Host 标头(如果它已在请求中定义)。

    来自Oleg Kalnichevski

    不应该乱用 HTTP 传输标头,例如“Host”(...),而是让 HttpClient 生成适当的标头值。(...)就“Host”标头而言,HttpClient只是不会覆盖现有值,假设用户知道得更好。

    奥列格

    参考:in case of a redirect a wrong host param is set to http header

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2014-01-19
      • 2011-08-03
      • 2021-04-10
      • 2022-06-18
      • 1970-01-01
      相关资源
      最近更新 更多