爲了讓Java程序來訪問我的谷歌驅動器,我需要使用JSON證書文件來創建oauth2.Credential(見https://console.developers.google.com)用於獲取一個訪問令牌。獲得從Java程序打開的瀏覽器谷歌授權要求已獲准
問題是,當我創建了憑據Java實例Java程序打開Internet Explorer,並要求許可驅動器。
Credential credential = new AuthorizationCodeInstalledApp(flow
, new LocalServerReceiver())
.authorize("user")
;
如果我點擊按鈕 「允許」,將創建憑證和我得到的令牌。
System.out.println("token" + credential.getAccessToken());
的問題是,這個java程序將是一個批處理程序,所以我們不能要求批量點擊一個按鈕。
此外,在https://security.google.com/settings/security/permissions?pli=1我的硬盤已經獲准進入我的應用程序(應用程序名稱是GoogleTest)...
你知道如何讓沒有java程序打開的瀏覽器證書詢問許可? 謝謝
這裏全碼:
public static void getToken() {
HttpTransport httpTransport ;
InputStream inputStream;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
List<String> scope = Arrays.asList(DriveScopes.DRIVE);
inputStream = new FileInputStream("C:/dev/ws/mainAzure/GoogleTest/res/client_secret_jcb_inst.json");
InputStreamReader reader = new InputStreamReader(inputStream);
clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,reader);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport
, JSON_FACTORY
,clientSecrets
, scope)
.setAccessType("offline")
.setApprovalPrompt("force")
.build();
//Browser open when there is new AuthorizationCodeInstalledApp(...)
Credential credential = new AuthorizationCodeInstalledApp(flow
, new LocalServerReceiver())
.authorize("user")
;
System.out.println("token" + credential.getAccessToken());
} catch (Exception e) {
e.printStackTrace();
}
}
謝謝您的回答,但目標是讓程序從谷歌驅動器訪問數據,而無需手動干預注入訪問令牌。我正在尋找解決方案。你認爲無法自動獲取令牌嗎? –
查看Google API的已安裝應用程序流程。我認爲這就是你所需要的 –
這個操作只需要在程序的安裝過程中執行一次,一旦刷新標記被存儲,它不會再被詢問,批處理將使用刷新標記來再次獲得新的訪問標記,再次。 – Harold