从Web服务器(.txt文件)读取重定向文件并验证页面响应(“MalformedURLException:no protocol”)

时间:2014-12-30 16:58:01

标签: java selenium selenium-webdriver

第一次发帖,但使用过这个网站的次数比我记忆的多!我对编程非常陌生,我的任务是用Selenium WebDriver编写自动化测试脚本,这最终使我学习了一些基本的(对某些Java)。

我尝试做的是读取驻留在Web服务器上的文本文件(大型重定向文件),遍历每一行,最后检查页面的响应(我没有&#39) ; t真的编码了)。我已经创建了一个脚本来加载每个页面并声明它不是404,但我正在寻找一个能够通过希望测试更快的解决方案http响应。

文本文件中的行可能以下列格式显示:

myredirect http://www.example.com/apage.html //主机外部的网址

anotherredirect /apage.html //重定向和目标路径之间的单个空格,没有协议/主机

andanotherredirect /apage.html //重定向和目标路径之间有两个空格,同样没有协议/主机

我遇到以下失败:

  

java.net.MalformedURLException:无协议:

我感谢任何帮助!

public class RedirectTestFireFox {
WebDriver driver;
StringBuffer verificationErrors = new StringBuffer();


@Before
public void setUp() throws Exception {

    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testRedirectTestFireFox() throws InterruptedException, IOException {

    //read redirects from file on web server
    URL test = new URL("https://www.example.com/redirects.txt");

    //get the protocol (http or https)
    String protocol = test.getProtocol();

    //get the host of the supplied url
    String host = test.getHost();

    //create baseURL variable that appends protocol "://" and the host
    String baseURL= protocol + "://" + host;

    //do something to each URL in text file
    try (Scanner scan = new Scanner(test.openStream())){
        //while there is still another line in the redirects file...
        while(scan.hasNextLine()) {

            //assign value to "line" variable
            String line = scan.nextLine();

            if(line != null){

                String redirect = line.substring(0, line.indexOf(" "));

                //find the last instance of a space and then take what is to the right of that and assign it back to line variable
                line = line.substring(line.lastIndexOf(" ")+1, line.length());

                //trim off any blank spaces from either end
                line.trim();

                //test to see if the first character starts with "/"
                boolean firstChar = line.startsWith("/");

                //if firstChar is "/" append the baseURL variable to the redirect
                if(firstChar) {
                    line = baseURL + line;
                }

                URL u = new URL(line); //this is the where it fails!!!
                HttpURLConnection urlConnection =(HttpURLConnection) u.openConnection (); 
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                try {
                    int code = urlConnection.getResponseCode();
                    assertEquals(200, code);
                } catch (AssertionError e) {
                    System.err.println("Error found! " + redirect);
                }

            }

        }
    }

    }

@After
    public void tearDown() throws Exception {
    driver.close();
}

}

0 个答案:

没有答案