你不能使用此代码单独用java得到响应。 您需要使用java selenium驱动程序代码才能执行此操作。
使用下面的代码,以获得正确的回应:
private static int statusCode;
public static void main(String... args) throws IOException{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> links = driver.findElements(By.tagName("a"));
for(int i = 0; i < links.size(); i++){
if(!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))){
if(links.get(i).getAttribute("href").contains("http")){
statusCode= intgetResponseCode(links.get(i).getAttribute("href").trim());
if(statusCode == 403){
System.out.println("HTTP 403 Forbidden # " + i + " " + links.get(i).getAttribute("href"));
}
}
}
}
}
public static int getResponseCode(String urlString) throws MalformedURLException, IOException{
URL url = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}
否则你能做得到通过设置响应方法“HEAD” [如果一个简单的测试]响应。
希望它有帮助。干杯!
什么是你所观察到的OUTPUT(HTTP响应代码)?你期望什么?你观察到了什么?请分享细节。 –
即使有效的链接,我也只得到-1。对于有效的链接,我期望2XX。 –
在** catch block **中,输出例外情况为'return connection.getResponseCode();'没有执行,我怀疑会抛出异常。与我们分享堆栈跟踪。 –