使用HttpClient无法获取响应中的“location”头信息

5
位置头已经存在,我可以在浏览器中看到它: enter image description here 我正在使用org.apache.httpcomponents.httpclient发送带有cookie的http请求:
```
URI uri = new URIBuilder().setScheme("https").setHost("api.weibo.com").setPath("/oauth2/authorize").setParameter("client_id","3099336849").setParameter("redirect_uri","http://45.78.24.83/authorize").setParameter("response_type", "code").build();
HttpGet req1 = new HttpGet(uri);
RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
req1.setConfig(config);
req1.setHeader("Connection", "keep-alive");
req1.setHeader("Cookie", cookie);
req1.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
response = httpclient.execute(req1);

我谷歌了很多,尝试启用/禁用自动重定向,但似乎对我没用。那么,有人能告诉我如何像浏览器一样获取响应中的位置标头吗?


请分享您用于尝试禁用重定向的代码。 - Jan
2个回答

2

您无法看到'redirect location'头信息,因为HttpClient在给您响应之前就立即跟随了该重定向。

在设置HttpClient时,请尝试禁用重定向:disableRedirectHandling()

HttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();

查看此URL,您将会看到Location头信息:

URI uri = new URIBuilder().setScheme("https").setHost("www.googlemail.com").setPath("/").build();

https://api.weibo.com/oauth2/authorize?client_id=3099336849&redirect_uri=http://45.78.24.83/authorize&response_type=code 我得到了这个页面。当我使用HttpClient发送请求时,似乎没有授权。 - Araell
好的 - 我已经尝试了你的代码,使用浏览器和代码都得到了200的响应。 - Jan
所以问题不在于HttpClient没有接收到“location”头,而是服务器没有发送它 - Jan
那么我不能使用 cookie 跳过身份验证流程吗? - Araell
那是一个全新的问题...尝试在代码中设置浏览器发送的所有头信息。 - Jan
我会尝试的。非常感谢!:) - Araell

0

我发现了我的真正问题...我在代码中没有通过认证过程,所以我一直得到oauth2页面。在我设置了所有请求头之后,就像浏览器一样,最终我得到了正确的响应。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接