In this post, we will see how to get ping URL and get status of it. We will use HttpURLConnection to connect to url and if response code is not 200, then it is not connected.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package org.arpit.java2blog.client; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author java2blog.com * */ public class CheckPingStatusOfURLMain { public static void main(String args[]) throws Exception { String status1 = getStatus("https://www.java2blog.com"); System.out.println("Java2blog.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; } } |
When you run above program, you will get below output:
1 2 3 4 |
Java2blog is : On javablog2 is : Off |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.