如何验证远程服务器上文件是否存在

来源:互联网 发布:政府数据开放 编辑:程序博客网 时间:2024/05/15 12:22

没有废话,只有代码。

 

java.net.URL url = null;java.net.URLConnection urlCon;try {url = new java.net.URL("http://192.168.0.26:8086/defaultroot/upload/201012211525255316256830418.doc");urlCon = url.openConnection();String message = urlCon.getHeaderField(0);System.out.println(message);//文件存在打印‘HTTP/1.1 200 OK’ 文件不存在打印 ‘HTTP/1.1 404 Not Found’} catch (java.net.MalformedURLException e0) {} catch (java.io.IOException ie3) {}


 

优化代码

public static boolean exists(String URLName) {try {HttpURLConnection.setFollowRedirects(false);HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();con.setRequestMethod("HEAD");return (con.getResponseCode() == HttpURLConnection.HTTP_OK);} catch (Exception e) {e.printStackTrace();return false;}}


 

原创粉丝点击