'www.mysite.com/mySecretKey1' redirects to 'www.othersite.com/mySecretKey2'
in G.AppsScript:
var response = UrlFetchApp.fetch("https://www.mysite.com/mySecretKey1");
var headerString = response.getAllHeaders().toSource();
Logger.log(headerString);
//string 'www.othersite.com.my/SecretKey2' is not present in log.
How would the script discover the URL address that it is redirected to (i.e. the string 'www.othersite.com/mySecretKey2')?
UPDATE: More generally, how would the script discover the URL address from response
?
Expounding on the answer by Joseph Combs, here's a version that uses recursion to follow multiple redirects, returning only the ultimate canonical URL:
function getRedirect(url) {
var response = UrlFetchApp.fetch(url, {'followRedirects': false, 'muteHttpExceptions': false});
var redirectUrl = response.getHeaders()['Location']; // undefined if no redirect, so...
var responseCode = response.getResponseCode();
if (redirectUrl) { // ...if redirected...
var nextRedirectUrl = getRedirect(redirectUrl); // ...it calls itself recursively...
Logger.log(url + " is redirecting to " + redirectUrl + ". (" + responseCode + ")");
return nextRedirectUrl;
}
else { // ...until it's not
Logger.log(url + " is canonical. (" + responseCode + ")");
return url;
}
}
function testGetRedirect() {
Logger.log("Returned: " + getRedirect("http://wikipedia.org"));
}
This logs:
https://www.wikipedia.org/ is canonical. (200)
https://wikipedia.org/ is redirecting to https://www.wikipedia.org/. (301)
http://wikipedia.org is redirecting to https://wikipedia.org/. (301)
Returned: https://www.wikipedia.org/
There is a native support in UrlFetchApp to follow redirects. You should try to set:
followRedirects = true
In the options you providing to UrlFetchApp. Something like that:
var options = {
"followRedirects" : true
};
var result = UrlFetchApp.getRequest("http://your-url", options);
UPDATE: More generally, how would the script discover the URL address from response?
Counterintuitively, you need to disable redirection and not mute HttpExceptions, like so:
var followedPost = UrlFetchApp.fetch(properUrl, {'followRedirects': false, 'muteHttpExceptions': false});
Logger.log(followedPost.getHeaders()['Location']);
The object returned by .getHeaders() will contain the new location of the resource being requested. Access that new location with a new .fetch().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With