使用Java和selenium我想检查我的下载链接是否有效。我只想显示http状态代码。
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(baseUrl);
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
我试过这个但没有成功。
答案 0 :(得分:1)
我设法按照我想要的方式工作。我已经使用了.isEnabled()选项,如下所示使用TestNG;
@Test
public void testProductNavBar(){
assertTrue(driver.findElement(By.xpath("/html/body/nav[2]/div/div/ul/li[1]/a")).isEnabled());
}
希望它会对你有所帮助。
答案 1 :(得分:1)
我已经尝试过,它可以正常运行以验证链接的状态。我的代码在这里。
public static void verifyURLStatus(String URL) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(URL);
try {
HttpResponse response = client.execute(request);
// verifying response code and The HttpStatus should be 200 if not,
// increment invalid link count
// We can also check for 404 status code like response.getStatusLine().getStatusCode() == 404
int invalidLinksCount=0;
if (response.getStatusLine().getStatusCode() != 200)
invalidLinksCount++;
System.out.println(response.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
String URL="http://cdn.rentbyowner.com/sitemap/gz/site-map-0.xml.gz";
verifyURLStatus(URL);
答案 2 :(得分:0)
是。我们可以使用httpurl连接来验证下载链接。以下是可重复使用的代码。
public static void verifyLinkActive(String linkUrl)
{
try
{
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==200)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
}
else
{
System.out.println(linkUrl+" - is Dowm");
}
} catch (Exception e)
{
}
}
感谢。