Java中如何检查URL是否有效或存在

5

我正在编写一个Java程序,需要访问一系列URL,并需要首先确定该URL是否存在。我不知道如何处理这个问题,也找不到要使用的Java代码。

URL的格式如下:

http: //ip:port/URI?Attribute=x&attribute2=y

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

有人能提供一些代码建议吗?


你如何为RESTful API撰写文档? - NimChimpsky
5个回答

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
}

或者您可以像在 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
     } 
}

第一种方法对我有用……非常感谢这个帮助……现在我可以通过直接给出完整链接的方式像其他浏览器一样在浏览器中打开链接了……再次感谢。 - Noman
it will also help for me. - d3m0li5h3r

5
  1. URL格式不正确会导致异常。
  2. 要知道URL是否有效,只能访问该URL。没有其他方法。

您可以通过请求URL的头来减轻负载。


3
package com.my;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class StrTest {

public static void main(String[] args) throws IOException {

    try {
        URL url = new URL("http://www.yaoo.coi");
        InputStream i = null;

        try {
            i = url.openStream();
        } catch (UnknownHostException ex) {
            System.out.println("THIS URL IS NOT VALID");
        }

        if (i != null) {
            System.out.println("Its working");
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
           }
      }
  }

输出:此URL无效


1

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


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接