Java中如何ping网址并获得状态
时间:2020-02-23 14:34:21 来源:igfitidea点击:
在本教程中,我们将看到如何获取Ping URL并获得其状态。
我们将使用HTTPURLConnection连接到URL,如果响应代码不是200,则不会连接。
package org.igi.theitroad.client; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author theitroad.com * */ public class CheckPingStatusOfURLMain { public static void main(String args[]) throws Exception { String status1 = getStatus("https://www.theitroad.com"); System.out.println("theitroad.com is : " + status1); String status2 = getStatus("http://www.javablog2.com"); System.out.println("javablog2.com is : " + status2); } public static String getStatus(String url) throws IOException { String result = ""; try { URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("GET"); //Set connection timeout con.setConnectTimeout(3000); con.connect(); int code = con.getResponseCode(); if (code == 200) { result = "On"; } } catch (Exception e) { result = "Off"; } return result; } }
运行上面的程序时,我们将得到以下输出:
theitroad is : On javablog2 is : Off