java 根據url連結判斷伺服器上的檔案是否存在有效
阿新 • • 發佈:2018-12-17
方法一: URL serverUrl = new URL("http://localhost:8090/Demo/clean.sql"); HttpURLConnection urlcon = (HttpURLConnection) serverUrl.openConnection(); String message = urlcon.getHeaderField(0); if (StringUtils.hasText(message) && message.startsWith("HTTP/1.1 404")) { System.out.println("不存在"); }else{ System.out.println("存在"+message); } 方法二: URL url = new URL("http://localhost:8090/Demo/clean.sql"); HttpURLConnection urlcon2 = (HttpURLConnection) url.openConnection(); Long TotalSize=Long.parseLong(urlcon2.getHeaderField("Content-Length")); if (TotalSize>0){ System.out.println("存在"); }else{ System.out.println("不存在"); }
String filepath ="http://22.58.123.146:8002/bidpu/upload/E3502000072/20180426/1984fa0b9f6/招告/20180426招標公告.pdf"
try {
URL pathUrl = new URL(filepath);
HttpURLConnection urlcon = (HttpURLConnection) pathUrl.openConnection();
if(urlcon.getResponseCode()>=400){
System.out.println("檔案不存在");
}else{
System.out.println("檔案存在");
}
}catch (Exception e) {
System.out.print("請求失敗");
}