gpt4 book ai didi

google-apps-script - 使用什么 Google Apps 脚本方法来获取重定向的 URL?

转载 作者:行者123 更新时间:2023-12-02 19:21:52 24 4
gpt4 key购买 nike

“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.

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

更新:更一般地说,脚本如何从响应中发现URL地址?

最佳答案

阐述answer by 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"));
}

此日志:

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/

关于google-apps-script - 使用什么 Google Apps 脚本方法来获取重定向的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27098169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com