我正在试图找出如何检查网址是否为404的逻辑或是否超时。我似乎无法弄明白!
这是我到目前为止所做的:
while (i < retries){
try {
response = Jsoup.connect(url)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(10000)
.execute();
success = true;
break;
} catch (IOException e) {
success = false;
}
System.out.println("Attempt " + i + " " + url);
i++;
}
}
public int getUrlStatus(){
if(success){
int statusCode = response.statusCode();
return statusCode;
}else {
return 404;
}
}
根据我的理解,这将告诉我,如果页面超时,页面404不会。我该如何检查?
答案 0 :(得分:3)
连接时可以抓住SocketTimeoutException
:
try {
response = Jsoup.connect(url)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(10000)
.execute();
success = true;
break;
} catch (SocketTimeoutExceptione) {
success = false;
System.out.println("Timeout occured");
}