Tuesday, December 23, 2008

Pinging to the Server Using Java

import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPingServer
{
public static void main(String[] args)
{
String sURL = "http://www.google.com";
String msg = null;

try
{
//Creates a URL object from the String representation.
URL url = new URL(sURL);

//Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

//use the URL connection for output only
httpURLConnection.setDoOutput(true);
httpURLConnection.setAllowUserInteraction(false);

final int responseCode = httpURLConnection.getResponseCode();
final String responseMessage = httpURLConnection.getResponseMessage();

if (responseCode != 200)
{
msg = "failure: " + responseCode + " " + responseMessage + " for URL: " + sURL;
}
else
{
msg = "success";
}
}
catch (Exception e)
{
msg = "failure: " + e + " for URL: " + sURL;
}

System.out.println(msg);
}
}

No comments:

Post a Comment