使用HttpClient.Execute(HttpGet)重定向后获取URL

use*_*412 7 java http-get httpresponse httpclient

我已经搜索了一段时间,但我找不到明确的答案.我正在尝试登录网站. https://hrlink.healthnet.com/ 此网站重定向到不合作的登录页面.我必须将我的登录凭据发布到重定向的URL.

我正在尝试用Java编写代码,但我不明白如何从响应中获取URL.它可能看起来有点乱,但我在测试的时候就是这样.

    HttpGet httpget = new HttpGet("https://hrlink.healthnet.com/");
    HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();

    String redirectURL = "";

    for(org.apache.http.Header header : response.getHeaders("Location")) {
        redirectURL += "Location: " + header.getValue()) + "\r\n";
        }        

    InputStream is;
    is = entity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
            sb.append(line + "\n"); 
    } 
    is.close(); 

    String result = sb.toString();
Run Code Online (Sandbox Code Playgroud)

我知道我被重定向,因为我的结果字符串显示的是实际的登录页面,但我无法获得新的URL.

在FireFox中我使用的是TamperData.当我导航到这个网站时https://hrlink.healthnet.com/我有一个GET,其中包含302 - Found和Login Page的位置.然后另一个GET到实际的登录页面

非常感谢任何帮助,谢谢.

yor*_*rkw 9

查看w3c文档:

10.3.3 302找到

临时URI应该由响应中的Location字段给出.除非请求方法是HEAD,否则响应的实体应该包含一个带有指向新URI的超链接的短超文本注释.

如果收到302状态代码以响应GET或HEAD以外的请求,则用户代理不得自动重定向请求,除非用户可以确认,因为这可能会改变发出请求的条件.

一种解决方案是使用POST方法来破坏客户端的自动重定向:

HttpPost request1 = new HttpPost("https://hrlink.healthnet.com/");
HttpResponse response1 = httpclient.execute(request1);

// expect a 302 response.
if (response1.getStatusLine().getStatusCode() == 302) {
  String redirectURL = response1.getFirstHeader("Location").getValue();

  // no auto-redirecting at client side, need manual send the request.
  HttpGet request2 = new HttpGet(redirectURL);
  HttpResponse response2 = httpclient.execute(request2);

  ... ...
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.