gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:31 24 4
gpt4 key购买 nike

我正在编写一个 Java 程序,它访问一个 url 列表并且需要首先知道该 url 是否存在。我不知道该怎么做,也找不到要使用的 Java 代码。

网址是这样的:

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

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

谁能推荐一些代码?

最佳答案

您可以只使用 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
}
}

关于java - 检查 URL 是否有效或存在于 java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com