62,623
社区成员
发帖
与我相关
我的任务
分享import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PingTest {
public static void main(String[] args) throws IOException {
String url = "www.baidu.com";
// 方法一
System.out.println("方法一");
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ping " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String str = "";
while((str = br.readLine()) != null) {
str = str.trim();
if(str.length() > 0) {
System.out.println(str);
}
}
br.close();
// 方法二
System.out.println("方法二");
URL u = new URL("http://" + url);
try {
HttpURLConnection http = (HttpURLConnection)u.openConnection();
if(http.getResponseCode() != 200) {
System.out.println(url + " connection error.");
}else{
System.out.println(url + " connection success.");
}
}catch(Exception e) {
System.out.println(url + " connection error.");
}
}
}