0
我試圖從我的後端訪問Google表格,使用Spring MVC編寫。使用教程,我得到這樣的:從Spring MVC訪問Google表格
public static Sheets getSheetsService() throws IOException {
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, authorize())
.setApplicationName(APPLICATION_NAME)
.build();
}
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
ConcreteSheetsController.class.getResourceAsStream("/secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
創建的祕密在於它是這裏所描述的方法:https://developers.google.com/sheets/quickstart/java
這是「工作」,但應用程序的輸出爲我提供了一個鏈接。當我點擊它時,我的瀏覽器會要求我選擇Google帳號。如果我這樣做一切正常,但我想有一個更適合的服務器解決方案。我希望我的secret.json文件能夠讓我的應用程序登錄,而無需提供我自己的用戶帳戶。有什麼辦法可以做到這一點?
你可以嘗試看看服務帳戶在使用[的OAuth 2.0服務器到服務器的應用程序(https://developers.google.com/identity/protocols/OAuth2ServiceAccount)。您可以進行API調用,特別是在調用Cloud API訪問基於項目的數據而不是用戶特定的數據時。 – noogui