Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用HttpClient.Execute(HttpGet)在重定向后获取URL_Java_Httpclient_Httpresponse_Http Get - Fatal编程技术网

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

Java 使用HttpClient.Execute(HttpGet)在重定向后获取URL,java,httpclient,httpresponse,http-get,Java,Httpclient,Httpresponse,Http Get,我已经搜索了一段时间,没有找到一个明确的答案。我正在尝试登录一个网站。 此网站重定向到不一致的登录页面。我必须将我的登录凭据发布到重定向的URL 我正在尝试用Java编写代码,但我不知道如何从响应中获取URL。它可能看起来有点凌乱,但我在测试时是这样做的 HttpGet httpget = new HttpGet("https://hrlink.healthnet.com/"); HttpResponse response = httpclient.execute(httpget

我已经搜索了一段时间,没有找到一个明确的答案。我正在尝试登录一个网站。 此网站重定向到不一致的登录页面。我必须将我的登录凭据发布到重定向的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();
我知道我被重定向了,因为我的结果字符串显示的是实际的登录页面,但我无法获得新的URL

在FireFox中,我使用的是篡改数据。当我导航到这个网站时,我有一个302-Found的GET和登录页面的位置。然后再进入实际登录页面

非常感谢您的帮助。

请查看:

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);

  ... ...
}
希望这对您有所帮助。

可能的副本