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

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012