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

来源:互联网 发布:java中的多态 编辑:程序博客网 时间:2024/05/16 00:37

转载:http://blog.csdn.net/soundfly/article/details/6177535


没有废话,只有代码。

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. java.net.URL url = null;  
  2.   
  3. java.net.URLConnection urlCon;  
  4.   
  5. try {  
  6.   
  7.     url = new java.net.URL("http://192.168.0.26:8086/defaultroot/upload/201012211525255316256830418.doc");  
  8.   
  9.     urlCon = url.openConnection();  
  10.   
  11.     String message = urlCon.getHeaderField(0);  
  12.   
  13.     System.out.println(message);//文件存在打印‘HTTP/1.1 200 OK’ 文件不存在打印 ‘HTTP/1.1 404 Not Found’  
  14.   
  15. catch (java.net.MalformedURLException e0) {  
  16.   
  17. catch (java.io.IOException ie3) {  
  18.   
  19. }  


 

优化代码

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static boolean exists(String URLName) {  
  2.         try {  
  3.             HttpURLConnection.setFollowRedirects(false);  
  4.             HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();  
  5.             con.setRequestMethod("HEAD");  
  6.             return (con.getResponseCode() == HttpURLConnection.HTTP_OK);  
  7.         } catch (Exception e) {  
  8.             e.printStackTrace();  
  9.             return false;  
  10.         }  
  11.     }  

0 0
原创粉丝点击