Created
October 16, 2012 14:50
-
-
Save sbglasius/3899754 to your computer and use it in GitHub Desktop.
Groovy function that will follow a number of redirects to get the real URL of a webpage/service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def findRealUrl(url) { | |
HttpURLConnection conn = url.openConnection() | |
conn.followRedirects = false | |
conn.requestMethod = 'HEAD' | |
if(conn.responseCode in [301,302]) { | |
if (conn.headerFields.'Location') { | |
return findRealUrl(conn.headerFields.Location.first().toURL()) | |
} else { | |
throw new RuntimeException('Failed to follow redirect') | |
} | |
} | |
return url | |
} |
really cool snippet! but note: a requestMethod of "GET" might in some cases be more accurate. It was in our case
numerous servers (ie amazon.com) return a 50x when given a HEAD request...
def findRealUrl(url, METHOD='HEAD') {
HttpURLConnection conn = url.openConnection()
conn.followRedirects = false
conn.requestMethod = METHOD
conn.connect()
if(conn.responseCode in [301,302]) {
if (conn.headerFields.'Location') {
return findRealUrl(conn.headerFields.Location.first().toURL())
} else {
throw new RuntimeException('Failed to follow redirect')
}
}
return url
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you are missing a url.connect() statement before testing the responseCode.