谷歌驱动器API通过谷歌应用引擎
-
12-12-2019 - |
题
我试图通过使用谷歌驱动器API 应用程序身份 google App Engine提供的界面。这基本上允许我的web应用程序与Google的Api进行通信 从服务器到服务器.
我不需要我的用户登录,我只需要显示我自己的Google云端硬盘文档。
但是,在我设置了所有适当的值和范围,并在控制台页面上启用所有正确的Google云端硬盘旋钮后,我仍然得到这个简单的GET请求 https://www.googleapis.com/drive/v2/files
:
{ "error": { "errors": [ { "domain": "usageLimits", "reason": "dailyLimitExceededUnreg", "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "extendedHelp": "https://code.google.com/apis/console" } ], "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." }}
怎么了?我错过了什么?下面是实际执行请求的代码-有趣的是,如果我使用其他Api(如URL缩短器API),它会很好地工作:
var scopes = new java.util.ArrayList();
scopes.add("https://www.googleapis.com/auth/drive");
var appIdentity = AppIdentityServiceFactory.getAppIdentityService();
var accessToken = appIdentity.getAccessToken(scopes);
var url = new URL("https://www.googleapis.com/drive/v2/files");
var connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Authorization", "OAuth " + accessToken.getAccessToken());
编辑
如果我只是更改API以使用 urlshortner
API例如,它的工作原理:
var url = new URL("https://www.googleapis.com/urlshortener/v1/url/history");
和输出:
{ "kind": "urlshortener#urlHistory", "totalItems": 0, "itemsPerPage": 30}
所以一定有什么不与谷歌驱动器和应用程序身份工作?
编辑2
我从这里的正确答案中找到了一些帮助: https://stackoverflow.com/a/12526286/50394
但它正在谈论在Google Apps上设置客户端API范围,而我没有使用Google Apps,我只是使用Google App Engine的域 foo.appspot.com
解决方案
您得到的403错误意味着您的GET中没有授权标头。逻辑是,没有授权头,你是匿名的(你是军团等等等等:-))。匿名使用的驱动器配额为零,因此消息。URL shortener具有更高的匿名配额,因此它可以工作。
我建议您将URL更改为指向您自己的http服务器,并检查您实际发送的标头。
其他提示
AFAICT你应该使用 Bearer
在授权头中。
可能发生的事情是,Drive API无法识别服务帐户(因为错误的标题?),因此将其视为匿名请求,因为没有 key
也没有提供参数(参见 常见查询参数).
试试这个:
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
或者您可以尝试将令牌添加为 access_token
查询参数。
我认为您至少应该设置一个启用了Drive API的API控制台条目 https://code.google.com/apis/console 一旦你创建了这个,你会得到一个ID,你可以在你的GoogleCredential对象中使用。从GoogleCredential对象中,您可以获得比添加到请求中更多的访问令牌。
我在这里读到的(通过服务帐户谷歌驱动器)是您使用稍微不同的样式,使用从开发人员控制台检索的API密钥。
我的相关部分是生成一个"服务器应用程序的密钥",然后使用这种技术,我没有读过 其他地方!
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
AppIdentityCredential credential =
new AppIdentityCredential.Builder(DriveScopes.DRIVE).build();
// API_KEY is from the Google Console as a server API key
GoogleClientRequestInitializer keyInitializer =
new CommonGoogleClientRequestInitializer(API_KEY);
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential)
.setGoogleClientRequestInitializer(keyInitializer)
.build();