2016-08-23 76 views
1

我正在嘗試編寫一個從電子表格中讀取數據的程序。我知道我必須使用OAuth或API密鑰,但是我完全失去了如何在我的程序中實現這樣的系統。我環顧四周,發現了很多例子和「教程」,但是我沒有得到任何一個例子(我對編程相對比較陌生)。 所以有人可以用最簡單的方式解釋我如何實現一個系統,使我可以驗證我的程序,以便我可以從電子表格中讀取數據(只有auth部分,剩下的我想我想通了)。 如果相關,電子表格可以公開,它只是一列數據。我使用Eclipse作爲我的環境。使用OAuth 2.0 for Google從電子表格中獲取數據

問候

回答

1

按照本Java Quickstart指示的步驟。

第1步:打開谷歌API表

一個。使用此嚮導在Google Developers Console中創建或選擇項目並自動打開API。點擊繼續,然後轉到憑據。

b。在向項目頁面添加憑據上,單擊取消按鈕。

c。在頁面頂部,選擇OAuth許可屏幕選項卡。選擇一個電子郵件地址,輸入一個產品名稱(如果尚未設置),然後單擊保存按鈕。 d)。選擇Credentials選項卡,單擊Create credentials按鈕並選擇OAuth客戶端ID。

e。選擇應用程序類型Other,輸入名稱「Google Sheets API Quickstart」,然後單擊Create按鈕。

f。點擊確定關閉結果對話框。 g。

g。單擊客戶端ID右側的file_download(下載JSON)按鈕。 h。

h。將此文件移動到您的工作目錄並將其重命名爲client_secret.json。

當所有設置完成後,這是使用您下載的client_secret.json處理授權的代碼。

public static Credential authorize() throws IOException { 
     // Load client secrets. 
     InputStream in = 
      SheetsQuickstart.class.getResourceAsStream("/client_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; 
    } 
相關問題