【发布时间】:2015-12-09 04:45:09
【问题描述】:
我在设置程序以调用 Google Sheets API 时遇到问题。目前,我正在通过这种方式授权我的证书:
public static Credential authorize() throws IOException, GeneralSecurityException {
InputStream p12 = GoogleUtils.class.getResourceAsStream("/key.p12");
File file = new File("hi");
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(p12, outputStream);
outputStream.close();
// Build flow and trigger user authorization request.
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("8429209348-1nfuorcfko5pmqh2l0b1au968igchaoq@developer.gserviceaccount.com")
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(file)
.build();
return credential;
}
但是,我现在不知道如何处理这个凭证。在另一堂课中,我打开了SpreadsheetService,但我找不到使用Credential 对象实际授权的方法。我记得在我的一个旧项目中这样做过:
public GoogleDrive() {
/** Our view of Google Spreadsheets as an authenticated Google user. */
try {
InputStream p12 = BotPanel.class.getResourceAsStream("/key.p12");
File file = new File("hi");
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(p12, outputStream);
outputStream.close();
String emailAddress = "81607255786-225dt8i2s8q6qgi0lgg814p27mumqro2@developer.gserviceaccount.com";
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String[] SCOPESArray = { "https://spreadsheets.google.com/feeds", "https://spreadsheets.google.com/feeds/spreadsheets/private/full", "https://docs.google.com/feeds" };
final List<String> SCOPES = Arrays.asList(SCOPESArray);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(emailAddress).setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(file)
.build();
file.delete();
service = new SpreadsheetService("Test");
service.setOAuth2Credentials(credential);
} catch (Exception e) {
e.printStackTrace();
}
}
如您所见,我以同样的方式获得Credential,最后我可以只调用service.setOAuth2Credentials(credential);但在我的新项目中,这就是我得到的:
如您所见,不再有名为 .setOAuth2Credential(...) 的方法。
挖掘src代码,发现GoogleService类中的方法,只有@Beta注解。
@Beta
public void setOAuth2Credentials(Credential credential) {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setOAuth2Credentials(credential);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
这段代码用@Beta 注释有什么原因吗?是否有其他方式我应该授权调用工作表 api?或者有什么方法仍然可以使用这种方法进行授权? (那将是理想的)。
【问题讨论】:
标签: java google-api google-oauth