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

    技术2025-01-26  27

    没有废话,只有代码。

     

    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; } }

     

    最新回复(0)