我正在尝试使用服务器响应代码和页面标题验证网站的链接,通过下面显示的代码找到的服务器响应为200,并且所有页面的页面标题也相同。
代码如下:
if(url == null || url.isEmpty())
{
System.out.println("URL is either not configured for anchor tag or it is
empty");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else if(!url.startsWith(homePage)){
System.out.println("URL belongs to another domain, skipping it.");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else{
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode != 200){
System.out.println(url+" is a broken link");
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"broken_links",url);
}
else{
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
if (Actualtitle.contentEquals(unexpectedTitle)){
System.out.println(url+ " is a broken link");
objExcelFile.writeExcel(filePath,"broken_links",url);
} else {
System.out.println(url+ " is a valid link");
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"valid_links",url);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
标题完好无损,但链接在标题下方显示500错误。问题是,即使页面显示500错误,我得到的服务器响应代码为200,因此我无法确定此链接是否已损坏
这是我正在验证的页面问题的屏幕截图:
答案 0 :(得分:0)
一旦你将 connect()引入:
huc.connect();
您可以编写尽可能多的for()
循环来检查 Response Code
调用 getResponseCode()
方法的任何情况,如下所示:< / p>
if (huc.getResponseCode() == 200)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 500)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 404)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 402)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
System.out.println(
linkURL + " - " + huc.getResponseMessage() + " - " + huc.HTTP_NOT_FOUND);
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}