Error for HttpResponseCode cannot be resolved to a type while checking URL status code for links

后端 未结 1 589
无人共我
无人共我 2020-12-21 15:46

I wrote simple program for checking URL status code. But eclipse giving me error saying HttpResponseCode cannot be resolved to a type. What should I do.

impo         


        
相关标签:
1条回答
  • 2020-12-21 15:54

    As per How to get Response Status Code with Selenium WebDriver in Selenium WebDriver there is no direct method to check the response status code, so we have to use another library. You can use Apache HttpClient or REST-assured library from Jayway.

    httpResponseCodeViaGet()

    To use the method httpResponseCodeViaGet() you have to download and use the following import:

    import io.restassured.RestAssured;
    

    And then you can use:

    new HttpResponseCode().httpResponseCodeViaGet("http://www.google.com");
    

    Solution

    As an alternative you can use HttpURLConnection and openConnection() and you can use the following solution:

    package demo;
    
    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.chrome.ChromeDriver;
    
    public class BrokenLinks {
    
        public static void main(String[] args) throws Exception {
    
            String sDriverPath = "C:\\Utility\\BrowserDrivers\\chromedriver.exe";
            System.setProperty("webdriver.chrome.driver", sDriverPath);
            String statusCode;
            final String URL = "https://www.starwars.com/";
            WebDriver driver = new ChromeDriver();
            driver.get(URL);
            driver.manage().window().maximize();
            List<WebElement> socialMenu = driver.findElements(By.xpath("//div[@id='nav-external-links']//a")); 
            System.out.println("Total Amenities "  + socialMenu.size());
            for (WebElement e : socialMenu)
            {
                String href = e.getAttribute("href");
                System.out.println(e.getAttribute("href"));
                HttpURLConnection connection = (HttpURLConnection) new URL(href).openConnection();
                connection.connect();
                statusCode = connection.getResponseMessage();
                connection.disconnect();
                if(!statusCode.contains("200")) {
                    System.out.println(href + " gave a response code of " + statusCode);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题