使用 drive.files.export (Drive API v3) + API 密钥以文本/纯文本格式获取公共 G

Get content of public Google Doc in text/plain format with drive.files.export (Drive API v3) + API key

本文关键字:API 文本 格式 获取 export files drive Drive 使用 v3 密钥      更新时间:2023-09-26

我需要在网页中以文本/纯格式加载我的公共Google Doc的内容。

发现API"drive.files.export"似乎完全符合我的需求。

https://developers.google.com/drive/v3/reference/files/export
https://developers.google.com/apis-explorer/#search/drive/drive/v3/drive.files.export

以下是我创建的测试文件的链接:

https://drive.google.com/open?id=1L5XSb0mR4VrVagQLRkvdg9aSMjRgWdq0L6d7TK8Vslo

所以文件 ID 是:

1L5XSb0mR4VrVagQLRkvdg9aSMjRgWdq0L6d7TK8Vslo

我还在 Google 开发者控制台上创建了一个项目,启用了云端硬盘 API 并获得了 API 密钥:

AIzaSyCeVVoW3NbuoVrmW_pa5HtVSG2rxQyEDXs

通过阅读"JavaScript 的 API 客户端库"文档,我假设我不需要"OAuth 2.0"身份验证,因为我不会访问任何用户私有数据。所以 API 密钥应该是成功的。这个想法是用户不必执行任何授权。

https://developers.google.com/api-client-library/javascript/features/authentication

所以我想出了这个简单的代码:

<script type="text/javascript">
function makeRequest() {
    var request = gapi.client.drive.files.export({
        'fileId': '1L5XSb0mR4VrVagQLRkvdg9aSMjRgWdq0L6d7TK8Vslo',
        'mimeType': 'text/plain'
    });
    request.then(function(response) {
        console.log(response);
    }, function(err) {
        console.log('Error');
        console.log(err.result.error);
    });
}
function init() {
    gapi.client.setApiKey('AIzaSyCeVVoW3NbuoVrmW_pa5HtVSG2rxQyEDXs');
    gapi.client.load('drive', 'v3').then(makeRequest);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>

但它不起作用。我总是得到这样的回应:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "internalError",
    "message": "Internal Error"
   }
  ],
  "code": 500,
  "message": "Internal Error"
 }
}

但是当我尝试"drive.files.get"API(https://developers.google.com/apis-explorer/#search/drive/drive/v3/drive.files.get(仅用于测试目的时,我从API得到了正确的响应:

{
 "kind": "drive#file",
 "id": "1L5XSb0mR4VrVagQLRkvdg9aSMjRgWdq0L6d7TK8Vslo",
 "name": "test",
 "mimeType": "application/vnd.google-apps.document"
}

它是 drive.files.export API 的错误,这就是为什么它不适用于组合 API 密钥 + 公共文件,或者我错过了一些东西并且我在这里做错了什么?

我会很高兴得到任何帮助。

错误 500 是服务器错误。请参阅ON_SERVER_ERROR。对于此类错误,您可以做的是实现指数退避以再次触发请求。

如果发生服务器错误 (5xx(,则其必需的回退必需实现(HttpResponse(返回 true。