Java中有时候需要检查URL地址或远程文件是否存在或者能正常访问,需要用到HttpURLConnection对象的相应状态来判断,代码如下:
public static boolean checkUrlFileExists(String URLName){ try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
返回的是200状态,则代表了改远程URL或文件能正常访问或者下载了。