相关疑难解决方法(0)

如何检查URL是否存在或使用Java返回404?

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");
}
Run Code Online (Sandbox Code Playgroud)

这应该打印

exists
does not exists
Run Code Online (Sandbox Code Playgroud)

测试

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"); …
Run Code Online (Sandbox Code Playgroud)

java url http-status-code-404

72
推荐指数
5
解决办法
13万
查看次数

标签 统计

http-status-code-404 ×1

java ×1

url ×1