Wednesday, July 8, 2009

Reading the status code of HTTP Request !

Facebook

When you make an HTTP request to any server url throuh your client software, lets say IE, HTTP Status codes are returned by the server to the client software to determine the outcome of your request. There are five different classes of status code range. They are
Status codes 100-101
Status codes 200-206
Status codes 300-307
Status codes 400-417
Status codes 500-505

Following is a simple program written in groovy that checks and returns the status code of any url.

import java.net.URL;
def url
def message =""
boolean fail=true
def urlString="http://192.168.0.1/test/test.html"
println checkURL(urlString)

def checkURL(urlString){
int status_code
def tempmessage=""
URL URLserver = new URL("urlString");
try{
URLConnection connection = (HttpURLConnection)URLserver.openConnection();

status_code = connection.getResponseCode();


switch (status_code)
{
case 200:
tempmessage=" Connection Successful"
break;
case 401:
tempmessage="UnAuthorised"
break;
case 405 :
tempmessage= " Resource Not Found"
break;
case 408:
tempmessage="Request Time-out"
break;
case 500:
tempmessage="Internal Server Error"
break;
case 502:
tempmessage="Bad Gateway"
break;
case 503:
tempmessage="Service Temporarily Unavailable"
break;
default :
tempmessage= connection.getResponseMessage()
break;

}
}
catch (Exception exc){
tempmessage=exc

}

return "\n "+urlString+" :"+status_code+":"+tempmessage;

}




Visit http://www.w3.org/Protocols/HTTP/HTRESP.html for detail about the status codes.


3 comments:

Patrick said...

You've shown one of the downsides of groovy - poor static analysis.
You aren't using urlString within your checkURL method.

urlString.toURL() gives you the URL

URLConnection does not have a getResponseCode() so do you need to explicitly create a HttpURLConnection or does groovy/java automatically know because of the http:// prefix in the URL? In which case why do you have the HttpURLConnection cast in there?

Bishow Paudel said...

You are absolutely right ! I have made the correction on the code.

Thanks

Ted Naleid said...

You can also use the "responseMessage" property of the connection to get the same kind of information.

def getUrlResponse(urlString) {
def conn = new URL(urlString).openConnection()
"$urlString : ${conn?.responseCode} : ${conn?.responseMessage}"
}

println getUrlResponse("http://google.com")
// prints http://google.com : 200 : OK

println getUrlResponse("http://google.com/foo")
// prints http://google.com/foo : 404 : Not Found

Post a Comment

I love to entertain onymous user Comment !

Pages

 ©mytechtoday.com 2006-2010

 ©Mytechtoday.com, Learning from Experiences !

TOP