我在设置调用GoogleSheets 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;
}
但是,我现在不知道该怎么处理这个凭证了。在另一个类中,我打开了一个电子表格服务
,但我找不到实际使用凭证
对象进行授权的方法。我记得在我的一个老项目中这样做:
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.setOAuth2Creentials(凭据);但是在我的新项目中,这就是我得到的:
正如您所看到的,没有一个名为. setOAuth2Credential(...)
的方法了。
深入研究src代码,我在GoogleService
类中找到了该方法,只是它有@Beta注释。
@Beta
public void setOAuth2Credentials(Credential credential) {
GoogleAuthTokenFactory googleAuthTokenFactory = getGoogleAuthTokenFactory();
googleAuthTokenFactory.setOAuth2Credentials(credential);
requestFactory.setAuthToken(authTokenFactory.getAuthToken());
}
这段代码用@Beta注释有什么原因吗?是否有其他方法可以授权对sheets api的调用?或者,是否仍有某种方法可以使用此方法进行授权?(那将是理想的)。
答案很简单。我一直都有错误的依赖关系。确保您有gdata客户端版本1.47。这里有一个指向jar文件的链接http://mvnrepository.com/artifact/com.google.gdata/core/1.47.1.一旦我把它用作图书馆,我所有的问题都消失了:)