Skip to content

Instantly share code, notes, and snippets.

@sbglasius
Created October 16, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbglasius/3899754 to your computer and use it in GitHub Desktop.
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
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
}
@gferon
Copy link

gferon commented Jul 14, 2016

I think you are missing a url.connect() statement before testing the responseCode.

@dularion
Copy link

really cool snippet! but note: a requestMethod of "GET" might in some cases be more accurate. It was in our case

@gernotstarke
Copy link

numerous servers (ie amazon.com) return a 50x when given a HEAD request...

@mahmoudimus
Copy link

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