有没有办法将"Google Sheet Java API“与API key一起使用,而不是与示例中给出的OAuth一起使用
https://developers.google.com/sheets/api/quickstart/java
我知道您可以使用HTTP请求来获取带有API键的数据,但是我在想,是否有一种方法可以使用google提供的Java API来做到这一点,这样我就不必为每个请求解析JSON。
发布于 2020-08-03 20:43:34
我没有找到任何正式的方法来实现这一点,但我能够按照Acquiring and using an API key中的描述来实现
获得
密钥后,您的应用程序可以将查询参数
key=yourAPIKey
附加到所有请求URL。
通过使用请求拦截器并手动添加key
查询参数,如下所示:
private Sheets getSheets() {
NetHttpTransport transport = new NetHttpTransport.Builder().build();
JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer httpRequestInitializer = request -> {
request.setInterceptor(intercepted -> intercepted.getUrl().set("key", API_KEY));
};
return new Sheets.Builder(transport, jsonFactory, httpRequestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
}
public List<List<Object>> getValues(String spreadsheetId, String range) throws IOException {
return getSheets()
.spreadsheets()
.values()
.get(spreadsheetId, range)
.execute()
.getValues();
}
发布于 2018-12-24 00:47:05
是的,你可以,本质上你需要下面这样的东西:
public NetHttpTransport netHttpTransport() throws GeneralSecurityException, IOException {
return GoogleNetHttpTransport.newTrustedTransport();
}
public JacksonFactory jacksonFactory() {
return JacksonFactory.getDefaultInstance();
}
private Set<String> googleOAuth2Scopes() {
Set<String> googleOAuth2Scopes = new HashSet<>();
googleOAuth2Scopes.add(SheetsScopes.SPREADSHEETS_READONLY);
return Collections.unmodifiableSet(googleOAuth2Scopes);
}
public GoogleCredential googleCredential() throws IOException {
File serviceAccount = new ClassPathResource("serviceAccount.json").getFile();
return GoogleCredential.fromStream(new FileInputStream(serviceAccount))
.createScoped(googleOAuth2Scopes());
}
public Sheets googleSheets() {
return new Sheets(netHttpTransport(), jacksonFactory(), googleCredential());
}
你可以在这里阅读更多关于serviceAccount.json
的信息:https://cloud.google.com/iam/docs/creating-managing-service-account-keys
上面的代码摘自我与谷歌API集成的一个Spring Boot示例项目:https://github.com/ciscoo/spring-boot-google-apis-example
发布于 2021-09-28 08:32:22
您还可以使用以下代码:
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.setGoogleClientRequestInitializer(CommonGoogleClientRequestInitializer.newBuilder().setKey(API_KEY).build())
.build();
https://stackoverflow.com/questions/53901194
复制相似问题