How to ping URL and get the status in java

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.

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("http://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:

Java2blog is : On
javablog2 is : Off
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.