2

当我用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

呃???

4

3 回答 3

2

发生的事情是curl,您将获得一个302,它实际上是一个重定向到位置标头中的 URL。

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

为了证明这个尝试

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

并比较响应。

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

于 2009-10-27T17:32:38.647 回答
0

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

当你离开时会发生什么-D

于 2009-10-27T17:33:28.757 回答
0

添加这个

  method.setFollowRedirects(false); 

在执行方法之前。

默认情况下,HttpClient 会自动遵循重定向,但 Curl 不会。

于 2009-10-27T18:09:46.813 回答