Java 从web服务器(.txt文件)读取重定向文件并验证来自页面的响应(“MalformedURLException:无协议”)
第一次发帖,但是我使用这个网站的次数已经超过了我的记忆!我对编程非常陌生,我的任务是用SeleniumWebDriver编写自动化测试脚本,这最终使我学会了一些Java的基本知识 我试图做的是读取一个文本文件,一个驻留在web服务器上的大型重定向文件,遍历每一行,最后检查我还没有真正编码的页面的响应。我已经创建了一个脚本,加载每个页面并断言它不是404,但我正在寻找一个解决方案,希望通过测试http响应可以更快 文本文件中的行可能以以下格式显示: myredirect//主机外部的url anotherredirect/apage.html//重定向和目标路径之间只有一个空格,没有协议/主机 andanotherredirect/apage.html//重定向和目标路径之间有两个空格,同样没有协议/主机 我遇到了以下失败: java.net.MalformedURLException:无协议: 我感谢任何帮助Java 从web服务器(.txt文件)读取重定向文件并验证来自页面的响应(“MalformedURLException:无协议”),java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,第一次发帖,但是我使用这个网站的次数已经超过了我的记忆!我对编程非常陌生,我的任务是用SeleniumWebDriver编写自动化测试脚本,这最终使我学会了一些Java的基本知识 我试图做的是读取一个文本文件,一个驻留在web服务器上的大型重定向文件,遍历每一行,最后检查我还没有真正编码的页面的响应。我已经创建了一个脚本,加载每个页面并断言它不是404,但我正在寻找一个解决方案,希望通过测试http响应可以更快 文本文件中的行可能以以下格式显示: myredirect//主机外部的url ano
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();
}
}
Selenium在这方面绝对是错误的工具。尝试curl、wget、httpbuilder等。