Skip to content

Instantly share code, notes, and snippets.

@sagrawal31
Created August 7, 2018 06:56
Show Gist options
  • Save sagrawal31/a95e98e1f6e1522dcf5477961cf5b2d0 to your computer and use it in GitHub Desktop.
Save sagrawal31/a95e98e1f6e1522dcf5477961cf5b2d0 to your computer and use it in GitHub Desktop.
A simple Groovy script to get the final URL of a URL by hitting that URL and checking for 301, 302 response codes
URL getFinalURL(String url) {
getFinalURL(new URL(url))
}
URL getFinalURL(URL url) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection()
connection.setInstanceFollowRedirects(false)
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36")
connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8")
connection.addRequestProperty("Referer", "http://example.com/")
connection.connect()
int responseCode = connection.getResponseCode()
if (responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
String locationHeader = connection.getHeaderField("Location")
if (locationHeader.startsWith("/")) {
locationHeader = url.getProtocol() + "://" + url.getHost() + locationHeader
}
return getFinalURL(new URL(locationHeader))
}
return url
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment