Skip to content

Instantly share code, notes, and snippets.

@sbglasius
Created October 16, 2012 14:50
Show Gist options
  • 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
}
@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