The code to ping a URL from java application is as follows :
public static void pingUrl(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
urlConn.connect();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Ping to "+address +" was success");
}
} catch (final IOException e) {
e.printStackTrace();
}
}
With response time:
public static void pingUrlWithResponseTime(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
final long startTime = System.currentTimeMillis();
urlConn.connect();
final long endTime = System.currentTimeMillis();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Time (ms) : " + (endTime - startTime));
System.out.println("Ping to "+address +" was success");
}
} catch (final IOException e) {
e.printStackTrace();
}
}