String urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_001.pdf";
URL url = new URL(urlString);
if(/* Url does not return 404 */) {
System.out.println("exists");
} else {
System.out.println("does not exists");
}
urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_190.pdf";
url = new URL(urlString);
if(/* Url does not return 404 */) {
System.out.println("exists");
} else {
System.out.println("does not exists");
}
này nên inCách kiểm tra xem một URL có tồn tại hay trả lại 404 bằng Java không?
exists
does not exists
THI
public static String URL = "http://www.nbc.com/Heroes/novels/downloads/";
public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
URL u = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}
System.out.println(getResponseCode(URL + "Heroes_novel_001.pdf"));
System.out.println(getResponseCode(URL + "Heroes_novel_190.pdf"));
System.out.println(getResponseCode("http://www.example.com"));
System.out.println(getResponseCode("http://www.example.com/junk"));
Output
SOLUTION
Thêm dòng tiếp theo trước khi .connect() và đầu ra sẽ là 200, 404, 200, 404
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
Tôi không thấy sự cố trong thử nghiệm của bạn. Trong trình duyệt của tôi, tôi không nhận được nội dung cho kết quả thứ hai, nhưng tôi không nhận được 404 –
Trong thực tế, tôi xuất hiện để có được một trang HTML phần lớn trống –
Trang web đó dường như cung cấp nội dung hợp lệ cho hầu hết mọi thứ. ví dụ. www.nbc.com/junk. Hãy thử với http://www.example.com/junk.html –