HttpURLConnection显示不正确的状态

时间:2017-05-09 10:42:37

标签: selenium selenium-webdriver

我正在尝试使用Selenium Webdriver通过检查http状态来检查我的网站/ cms上的每个链接是否正常工作。为此,我在Selenium Webdriver中使用HttpURLConnection类。这是我正在执行的代码:

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class checkingLinks {

public static void main(String[] args)
{
    WebDriver driver=new FirefoxDriver();

    driver.manage().window().maximize();

    driver.get("link_to_cms");

    driver.findElement(By.id("username")).clear();
    driver.findElement(By.id("username")).sendKeys("my_login");
    driver.findElement(By.id("password")).clear();
    driver.findElement(By.id("password")).sendKeys("my_passwod");
    driver.findElement(By.xpath("//button[@type='submit']")).click();

    List<WebElement> links=driver.findElements(By.tagName("a"));

    System.out.println("Total links are "+links.size());

    for(int i=0;i<links.size();i++)
    {

        WebElement ele= links.get(i);

        String url=ele.getAttribute("href");

        verifyLinkActive(url);

    }

}

public static void verifyLinkActive(String linkUrl)
{
    try
    {
        URL url = new URL(linkUrl);

        HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();

        httpURLConnect.setConnectTimeout(3000);

        httpURLConnect.connect();

        System.out.println(linkUrl+" - "+httpURLConnect.getResponseCode());


    } catch (Exception e) {

    }
}

}

问题是,在结果中所有链接都获得http状态200,但我知道其中很少有http状态为500.您是否知道它是如何可能的?我是否在上面的代码中犯了一个错误的结果?

1 个答案:

答案 0 :(得分:0)

我没有看到您的HttpURLConnection发送HTTP请求。它只是打开一个连接。

此外,您在进行身份验证(登录)时收到的Cookie需要在后续请求中作为标头发送。