javascript - 在 Google App 脚本中请求 API 数据时,有没有办法使用特定的 IP?

标签 javascript api google-apps-script

我正在使用 Google 应用脚本从网站请求 API 数据,然后将收到的数据记录在 Google 表格中。我遇到的问题是,我请求数据的网站需要两件事:我的身份验证 key 和特定的(静态)IP 地址。它会自动记录发出请求的 IP 地址,如果我使用错误的 IP 地址,它不会让我获取数据。不幸的是,Google App Script API 请求使用一系列动态 IP,并且我最多只能允许 5 个不同的 IP 使用我的身份验证 key 。有没有办法指定我的 Google 应用脚本将使用哪个 IP 地址发送 API 请求?

下面你可以看到我的代码;当 IP 地址与我在网站上写的内容匹配时,一切都会非常有效,但如果它使用未知的 IP 地址,则会返回未定义。

function fetchAPI(tag) {
  var url = 'https://myurl'
    + tag;
  var token = {'muteHttpExceptions': true};
  token.headers = {'Accept': 'application/json','authorization': 'my auth key'};
  var response = UrlFetchApp.fetch(url, token);
  return JSON.parse(response);
}

我想到的另一个选择是创建多个 API key ,每 5 个 IP 地址一个,但这样做的问题是 Google 的 IP 范围涵盖数百个不同的地址:https://developers.google.com/apps-script/guides/jdbc#accessing

如果您能想到任何可能有帮助的事情,我们将不胜感激!或者,如果您能想到一种通过静态 IP 地址代理我的请求的方法(无需付费托管我自己的网站),请告诉我!

最佳答案

根据这个blog ,作者观察到了 google 脚本中 IP 使用的模式:

Therewere two clear observations:

  • IP may vary in consecutive calls within one trigger
  • There is a clear rotation of the IPs, sometimes there is a group of 7 consecutive calls with the same IP, sometimes 6. But in general there are always groups.

因此可以采用重复调用服务器直到成功的解决方案:

function batchRequest(userLogin, userPassword, webapiKey, resource, attributes, values ){

    var token = requestToken(userLogin, userPassword, webapiKey );   // requestToken method uses UrlFetchApp.fetch
     var result = request(resource, token, attributes, values); 

    /** requestToken method uses UrlFetchApp.fetch with options.muteHttpExceptions set to true so that we can read the response code **/

     var i = 0;
     while (result.getResponseCode() == 500 && i < 10){
     token = requestToken(userLogin, userPassword, webapiKey ); //  requestToken method uses UrlFetchApp.fetch
     result = request(resource, token, attributes, values);
     i++;
     }
     return result;
    }

您可以根据最佳结果改变迭代次数。

关于javascript - 在 Google App 脚本中请求 API 数据时,有没有办法使用特定的 IP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47104530/

相关文章:

javascript - 带有 InfoBubbles 的 Google map

node.js - 使用 Node/Express 发送后不断收到 "Can' t set headers

javascript - 查找一列中的颜色并从另一列中获取数据

javascript - 使用 Advanced Drive Services 创建电子表格

csv - 从Google Apps脚本中的类似csv的文件中读取数据

javascript - Node 内存使用情况和内存不足

javascript - 谷歌浏览器 Javascript 链接错误

javascript - 如何在查询字符串中使用撇号嵌入值

api - 不使用 WHMCS API 插入的自定义字段

python - 通过 Python API 获取所有 Woocommerce 订单