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:
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?
You are absolutely right ! I have made the correction on the code.
Thanks
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 !