What Google AppsScript method is used to get the URL of a redirect?

google-apps-script, redirect, urlfetch

Solution

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/

Problem

'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`?

Original source