【问题标题】:Redirect with Curl/HttpClient: header "Location" missing使用 Curl/HttpClient 重定向:缺少标头“位置”
【发布时间】:2010-12-10 13:58:56
【问题描述】:

当我通过 curl

获得以下网址时
curl -D headers.http "http://www.springerlink.com/index/10.1007/s00453-007-9157-8"

文件 headers.http 包含一个“位置”标头:

HTTP/1.1 302 Found
Date: Tue, 27 Oct 2009 17:00:20 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Location: http://www.springerlink.com/link.asp?id=c104731297q64224
Set-Cookie: CookiesSupported=True; expires=Wed, 27-Oct-2010 17:00:20 GMT; path=/
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 173

但是当我使用 apache httpclient 库时,这个“Location:”标头丢失了 (?)。

int status = httpClient.executeMethod(method);
if(status!=HttpStatus.SC_OK &&
status!=HttpStatus.SC_MOVED_TEMPORARILY &&
status!=HttpStatus.SC_MOVED_PERMANENTLY
    )
    {
    throw new IOException("connection failure for "+url+" status:"+status);
    }
Header header=method.getResponseHeader("Location");
if(header==null )
    {

    for(Header h:method.getResponseHeaders())
        {
        LOG.info(h.toString());
        }

    throw new IOException(
        "Expected a redirect for "+url
        );
    }

我在下面列出了标题:

INFO: Date: Tue, 27 Oct 2009 17:05:13 GMT
INFO: Server: Microsoft-IIS/6.0
INFO: X-Powered-By: ASP.NET
INFO: X-AspNet-Version: 2.0.50727
INFO: Set-Cookie: ASP.NET_SessionId=js1o5wqnuhuh24islnvkyr45; path=/; HttpOnly
INFO: Cache-Control: private
INFO: Content-Type: text/html; charset=utf-8
INFO: Content-Length: 17245

呃???

【问题讨论】:

    标签: java redirect http-headers http-status-code-302 apache-commons-httpclient


    【解决方案1】:

    发生了什么是 curl ,你会得到一个 302 这实际上是一个重定向到位置标头中的 URL。

    使用 Apache httpclient,它会为您进行重定向,并将请求中的标头返回到重定向到的位置。

    为了演示这个尝试

    curl -D headers.http "http://www.springerlink.com/link.asp?id=c104731297q64224"
    

    并比较响应。

    编辑:如果您使用 curl 跟随每个位置标题,实际上大约有 4 个重定向。

    【讨论】:

      【解决方案2】:

      http://www.springerlink.com/index/10.1007/s00453-007-9157-8 实际上是一个重定向。由于-D 选项表示“仅标题”,因此第一个不会重定向到指定的Location: ...,而第二个是。看一下 Content-Length,它有很大的不同。

      如果您忽略了-D,会发生什么?

      【讨论】:

      • 使用我的 curl 版本“-D/--dump-header 将标题写入此文件”。它不是“仅标题”。不管有没有 -D ,结果都是一样的。
      • 所以看起来低级 curl 命令没有遵循重定向,而您的 java curl 客户端。它。
      【解决方案3】:

      添加这个

        method.setFollowRedirects(false); 
      

      在执行方法之前。

      HttpClient 默认自动跟随重定向,但 Curl 不会。

      【讨论】:

        猜你喜欢
        • 2018-05-09
        • 2019-02-25
        • 2013-10-08
        • 2021-09-04
        • 2014-01-10
        • 1970-01-01
        • 1970-01-01
        • 2017-06-21
        • 2016-12-20
        相关资源
        最近更新 更多