Google Apps 脚本 UrlFetchApp 返回未经授权的错误 401

Spe*_*cer 2 export google-docs urlfetch google-apps-script

这是我正在使用的代码。

function doc_to_html(id)
{
  var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
var param = 
    {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions:true,
    };
 var html = UrlFetchApp.fetch(url,param).getContentText();
  Logger.log(html);
}
Run Code Online (Sandbox Code Playgroud)

它曾多次进行测试,但现在返回“未经授权的错误 401”。更准确地说,它正在返回:

<html>
<head>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Run Code Online (Sandbox Code Playgroud)

我查看了所有能找到的有关 UrlFetchApp 的文档,没有看到任何配额或限制。我检查了脚本范围,并且https://www.googleapis.com/auth/script.external_request已获得授权。

The*_*ter 5

提供的范围不足以访问该文档。要访问它,您还需要文档范围。编辑清单文件以具有以下范围:

"oauthScopes": ["https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/documents"],
Run Code Online (Sandbox Code Playgroud)

或者在脚本中添加对 Document App 的虚拟调用:

DocumentApp.getActiveDocument();
Run Code Online (Sandbox Code Playgroud)

根据Tanaike的评论,文档范围似乎还不够,但电子表格范围也是需要的,即使我们不访问电子表格。或者,需要 Drive 的只读范围。

电子表格+文档范围:

显现:

"oauthScopes": ["https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/documents"
    "https://www.googleapis.com/auth/spreadsheets"],
Run Code Online (Sandbox Code Playgroud)

或者在脚本中添加对 Document App+SpreadsheetApp 的虚拟调用:

//DocumentApp.getActiveDocument();
//SpreadsheetApp.getActive();
Run Code Online (Sandbox Code Playgroud)

驱动范围:

显现:

"oauthScopes": ["https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/drive.readonly"],
Run Code Online (Sandbox Code Playgroud)

或者在脚本中添加对 DriveApp 的虚拟调用:

//DriveApp.getFiles()
Run Code Online (Sandbox Code Playgroud)