Reindirizzamento con Curl / HttpClient: header & # 8220; Location & # 8221; mancante
Domanda
quando ottengo il seguente URL con curl
curl -D headers.http "http://www.springerlink.com/index/10.1007/s00453-007-9157-8"
il file headers.http contiene un " Location " intestazione:
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
ma quando ho usato la libreria httpclient di apache questa " Posizione: " mancava l'intestazione (?).
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
);
}
Ho elencato le intestazioni di seguito:
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
uhh ???
Soluzione
Quello che sta succedendo è che con curl
, stai ottenendo un 302 che in realtà è un reindirizzamento, all'URL nell'intestazione della posizione.
Con Apache httpclient sta eseguendo il reindirizzamento per te e restituendo le intestazioni dalla richiesta alla posizione di reindirizzamento.
Per dimostrarlo, prova
curl -D headers.http "http://www.springerlink.com/link.asp?id=c104731297q64224"
e confronta la risposta.
modifica: in realtà ci sono circa 4 reindirizzamenti lì se segui ogni intestazione di posizione con il ricciolo.
Altri suggerimenti
http://www.springerlink.com/index/10.1007 / s00453-007-9157-8 è in realtà un reindirizzamento. Dal momento che l'opzione -D
significa " solo intestazioni " ;, il primo non reindirizza alla Posizione: ...
specificata, mentre il secondo è. Dai un'occhiata a Content-Length, è molto diverso.
Cosa succede quando si esclude -D
?
Aggiungi questo
method.setFollowRedirects(false);
Prima di eseguire il metodo.
HttpClient segue automaticamente il reindirizzamento di default, ma Curl no.