我正在编写一个Java程序,它会点击一个url列表,需要先知道url是否存在。我不知道如何解决这个问题,无法找到要使用的java代码。
网址如下:
http: //ip:port/URI?Attribute=x&attribute2=y
这些是我们内部网络上的URL,如果有效,将返回XML。
有人可以推荐一些代码吗?
答案 0 :(得分:10)
您可以使用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
}
}
答案 1 :(得分:5)
您可以通过从网址请求标头来减少负载。
答案 2 :(得分: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();
}
}
}
输出:此网址无效
答案 3 :(得分:1)
打开连接并检查响应是否包含有效的XML?这太明显了还是你在寻找其他魔法?
答案 4 :(得分:1)
您可能想要使用HttpURLConnection并检查错误状态: