Created
August 7, 2018 06:56
-
-
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
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
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