我正在使用SpreadsheetService,并且正在尝试从电子表格网址(https://spreadsheets.google.com/feeds/spreadsheets/private/full)获取提要。
我正在使用服务密钥进行身份验证。似乎验证正常,但是当我尝试获取提要时出现错误:
ServiceException(com.google.gdata.util.ServiceException:内部服务器错误)。
这是身份验证方法:
public static Credential authenticateWithServiceKey(GoogleApiProperties properties) throws IOException {
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("src/main/resources/prime-moment-274810-940d01c0244d.json"))
.createScoped(Collections.singleton(properties.getScope()));
return credential;
}
这就是我创建服务并使用上述方法中的Credential对象进行身份验证的方式:
public void init(GoogleApiProperties properties) throws IOException, GeneralSecurityException {
Credential credential = GoogleAuthentication.authenticateWithServiceKey(properties);
service = new SpreadsheetService(properties.getApplicationName());
service.setOAuth2Credentials(credential);
}
这就是我要获取电子表格列表的位置:
public List<String> getContentList() throws IOException, ServiceException {
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(SPREADSHEETS_URL);
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
// Return a list of spreadsheet names
return feed.getEntries().stream()
.map(entry -> entry.getTitle().getPlainText())
.collect(Collectors.toList());
}
异常是在service.getFeed
通话后立即发生的。
当我使用常规方法获取OAuth2.0凭据时,它可以正常工作,但需要人工干预(接受通过Google页面的连接)。
错误不在于凭证,而在于执行。看来您一切正常,因为这是服务器错误。
尽管Sheets API v3 已于2020年9月弃用,所以我还是建议您使用Sheets API v4 方法:获取电子表格的供稿。
如果您从以前的API转到Sheets API v4迁移-> 检索工作表元数据,则会发现:
如果您只想读取工作表属性,请将
includeGridData
查询参数设置为false以防止包含电子表格单元格数据。
因此,按照“ 方法:sheets.get”示例可以解决您的问题。
这是我使用的方法的简短版本:
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = "YOUR SPREADSHEET ID";
final String range = "Class Data!A2:E";
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
Sheets.Spreadsheets.Get request = service.spreadsheets().get(spreadsheetId);
request.setIncludeGridData(false);
//Sheets.Spreadsheets response = request.execute();
// TODO: Change code below to process the `response` object:
System.out.println(request.execute());
}
编辑
要列出电子表格,您必须通过Drive API来完成。
在这种情况下,通过方法Files: List
并在查询或q
参数上,输入电子表格MIME类型:mimeType = 'application/vnd.google-apps.spreadsheet'
您可以在快速入门中查看如何使用“文件:”列表
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句