May*_*hwa 7 java google-sheets google-sheets-api
有没有一种方法可以将“Google Sheet Java API”与 API 密钥一起使用,而不是使用其示例中给出的 OAuth
https://developers.google.com/sheets/api/quickstart/java
我知道你可以使用 HTTP 请求来获取带有 API 密钥的数据,但我在想是否有办法使用谷歌提供的 Java API 来做到这一点,这样我就不必为每个请求解析 JSON。
我没有找到任何官方方法来实现此目的,但我能够按照获取和使用 API 密钥中的描述来完成此操作:
获得 API 密钥后,您的应用程序可以将查询参数附加
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();
}
Run Code Online (Sandbox Code Playgroud)
是的,你可以,本质上你需要如下所示的东西:
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());
}
Run Code Online (Sandbox Code Playgroud)
您可以在serviceAccount.json此处阅读有关以下内容的更多信息:https ://cloud.google.com/iam/docs/creating-managing-service-account-keys
以上内容取自我与 Google API 集成的 Spring Boot 示例项目: https: //github.com/ciscoo/spring-boot-google-apis-example
| 归档时间: |
|
| 查看次数: |
1975 次 |
| 最近记录: |