使用 Google Apps 脚本进行身份验证以查询 Fusion Table

Authenticate to query a Fusion Table using Google Apps Script

我是 Google Apps 域的成员,我正在尝试使用代码示例来查询融合 table 但不断收到以下错误:

{
  "error": {
    "errors": [
      {
      "domain": "global",
      "reason": "required",
      "message": "Login Required",
      "locationType": "header",
      "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required"
  }
}

这是我使用的代码:

function myFunction() {

//Fusion Table
  var constructor = 'https://www.googleapis.com/fusiontables/v2/query?sql=';
  var fusionTableID = '1pJk********UY5l';
  var fusionTableAPIKey = 'AIza********AGV8';  //  Browser API Key
  var fusionTableQuery = 'SELECT * FROM ' + fusionTableID + '&key=' + fusionTableAPIKey;  
  var queryString = constructor + fusionTableQuery;

  var response = UrlFetchApp.fetch(queryString);

  var parsedResponse = JSON.parse(response.getContentText());

  Logger.log(parsedResponse);

}

不幸的是,由于域设置,我无法与域外的人共享任何文件。我已经查看了参考资料 here,但我不确定如何使其适应我正在做的事情。

我可以使用来自 Google 的示例字符串让脚本工作,所以我确信代码是正确的:

https://www.googleapis.com/fusiontables/v2/query?sql=SELECT * FROM%201KxVV0wQXhxhMScSDuqr-0Ebf0YEt4m4xzVplKd4&key=AIzaSyAm9yWCV7JPCTHCJut8whOjARd7pwROFDQ

提前谢谢你。

您需要在请求中传递授权 header,使用访问令牌或登录身份验证。它显示在您发布的 link 中。

无论如何,只使用 Fusion Table 高级服务要容易得多。要启用它,请转到资源 > 高级 Google 服务 > 融合 Tables API.

如果您还想手动拨打电话。至少启用该服务并放置一些假代码,以便 Apps 脚本可以为您请求 oAuth2 范围。例如

function noNeedToRun() //just to trigger the scope
  FusionTables.Query.sql('foo'); //although this is easier than UrlFetch`ing manually
}

function myFunction() {
  //...your same code
  var queryString = constructor + fusionTableQuery;

  var response = UrlFetchApp.fetch(queryString, {
    headers: { //this is what you're missing
        "Authorization": "Bearer " + ScriptApp.getOAuthToken(),
    }
  });

  var parsedResponse = JSON.parse(response.getContentText());

  Logger.log(parsedResponse);
}