我正在尝试编写一个Google App Engine应用程序,该应用程序使用Google表格API从Google云端硬盘访问电子表格。我在Google上找到了一个示例,其中显示了如何从Google应用引擎应用访问日历:https://github.com/google/google-api-java-client-samples/tree/master/calendar-appengine-sample
我把它作为基础并尝试用SpreadSheet调用替换Calendar调用。在此示例中,此代码访问日历数据:
static Calendar loadCalendarClient() throws IOException {
String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
Credential credential = newFlow().loadCredential(userId);
return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
}
但是,Sheets API不提供任何Sheets.Builder。相反,从另一个示例(https://developers.google.com/google-apps/spreadsheets/),我发现他们使用以下代码:
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
// TODO: Authorize the service object for a specific user (see other sections)
因此,诀窍是使用凭据授权Sheets服务。我试图合并这些例子,但没有成功:
String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
Credential credential = flow.loadCredential(userId); // the flow object which was used to create an OAuth flow
SpreadsheetService service = new SpreadsheetService("AppName");
credential.refreshToken();
service.setOAuth2Credentials(credential);
URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
调用service.getFeed方法后,我收到一个异常:
com.google.gdata.client.GoogleService$SessionExpiredException: OK
Token invalid - AuthSub token has wrong scope</TITLE>
Token invalid - AuthSub token has wrong scope</H1>
Error 401
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:570)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
任何想法如何解决?