getResponseCode()方法未返回预期的响应代码

时间:2019-11-13 08:01:50

标签: google-apps-script urlfetch

我对Google App脚本服务的getResponseCode()方法有2个问题。

1)“意外错误”

当我运行getResponseCode()方法时,出现“意外错误...”。

https://developers.google.com/apps-script/reference/url-fetch/http-response#getResponseCode()

var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
responseCode = response.getResponseCode();

Unexpected error: https://www.example.com/

※由于业务原因我无法告知网址。

HTTP响应状态代码不包含“意外错误”。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

请告诉我,发生此错误时实际上返回什么响应代码?

2)getResponseCode()方法未按预期工作

当我运行下面的代码时,我得到了“ 200”。

我期望“ 301”响应“ http ://google.com/”请求。

function myFunction() {
  var response = UrlFetchApp.fetch("http://google.com/");
 Logger.log(response.getResponseCode());
}

我认为getResponseCode()方法不会返回实际的http状态代码。

请告诉我为什么我得到“ 200”而不是“ 301”。

get 301 response in browser

get 200 response instead of 301

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为请求遵循重定向。查看UrlFetchApp.fetch()方法中的可用参数。您会看到followRedirects,默认为true

进行一些小的更改,您将获得预期的301

function myFunction() {
  var response = UrlFetchApp.fetch("http://google.com/", { followRedirects: false });
 Logger.log(response.getResponseCode());
}
相关问题