哪种Google AppsScript方法用于获取重定向的URL?

use*_*994 5 redirect google-apps-script

“ www.mysite.com/mySecretKey1”重定向到“ www.othersite.com/mySecretKey2”

在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.
Run Code Online (Sandbox Code Playgroud)

脚本将如何发现重定向到的URL地址(即字符串'www.othersite.com/mySecretKey2')?

更新:更一般而言,脚本将如何从中发现URL地址response

Chr*_*ris 5

解释约瑟夫·科姆斯(Joseph Combs)答案,这是一个使用递归进行多次重定向的版本,仅返回最终的规范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"));
}
Run Code Online (Sandbox Code Playgroud)

记录:

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/
Run Code Online (Sandbox Code Playgroud)

  • 伙计,我爱你。这正是我一直在寻找的。 (2认同)

Ido*_*een 1

UrlFetchApp 原生支持跟踪重定向。您应该尝试设置:

followRedirects = true
Run Code Online (Sandbox Code Playgroud)

在您提供给 UrlFetchApp 的选项中。像这样的东西:

var options = {
   "followRedirects" : true
 };
var result = UrlFetchApp.getRequest("http://your-url", options);
Run Code Online (Sandbox Code Playgroud)

  • “响应”中仍然缺少第一页或第二页的 URL 地址。 (2认同)