检查URL是否有效或是否存在于java中

Pod*_*dge 5 java url http

我正在编写一个Java程序,它会点击一个url列表,需要先知道url是否存在.我不知道该怎么做,无法找到要使用的java代码.

URL如下所示:

http: //ip:port/URI?Attribute=x&attribute2=y
Run Code Online (Sandbox Code Playgroud)

这些是我们内部网络上的URL,如果有效,将返回XML.

谁能建议一些代码?

sea*_*alz 11

你可以使用httpURLConnection.如果它无效,您将无法获得任何回报.

    HttpURLConnection connection = null;
try{         
    URL myurl = new URL("http://www.myURL.com");        
    connection = (HttpURLConnection) myurl.openConnection(); 
    //Set request to header to reduce load as Subirkumarsao said.       
    connection.setRequestMethod("HEAD");         
    int code = connection.getResponseCode();        
    System.out.println("" + code); 
} catch {
//Handle invalid URL
}
Run Code Online (Sandbox Code Playgroud)

或者您可以像从CMD那样ping它并记录响应.

String myurl = "google.com"
String ping = "ping " + myurl 

try {
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(ping);
    r.exec(ping);    
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String inLine;
    BufferedWriter write = new BufferedWriter(new FileWriter("C:\\myfile.txt"));

    while ((inLine = in.readLine()) != null) {             
            write.write(inLine);   
            write.newLine();
        }
            write.flush();
            write.close();
            in.close();              
     } catch (Exception ex) {
       //Code here for what you want to do with invalid URLs
     } 
}
Run Code Online (Sandbox Code Playgroud)


Sub*_*Sao 5

  1. 格式错误的网址会给您一个例外.
  2. 要知道你的网址是否有效,你必须点击网址.没有其他办法.

您可以通过从网址请求标头来减少负载.


jar*_*bjo 1

打开连接并检查响应是否包含有效的 XML?这是否太明显了,还是您正在寻找其他魔法?