2013-03-23 72 views
1

我一直在嘗試編寫一個使用谷歌加API的Web應用程序,我需要設置與Java的OAuth訪問,我搜索了很多,並發現谷歌Java啓動和其他例子和他們很混亂,我不知道我應該寫什麼代碼來獲得令牌 我希望如果有人能夠直接向我介紹如何通過java訪問OAuth,我看到了其他問題在stackoverflow.com但他們不是非常有幫助,我OAuth 2.0訪問與谷歌加API在Java中

所以任何幫助將是非常讚賞:)

回答

6

最新Google+ Java Quickstart是非常簡單的,也許你發現了奧爾德r項目在搜索時?另外,documentation for getting started on Google+ with Java應該可以幫助您順利完成任務。

下面的代碼片段使用the hybrid client/server flow當您展示了交換授權代碼的訪問令牌相關代碼:

 GoogleTokenResponse tokenResponse = 
      new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, 
       CLIENT_ID, CLIENT_SECRET, code, "postmessage").execute(); 
     // Create a credential representation of the token data. 
     GoogleCredential credential = new GoogleCredential.Builder() 
      .setJsonFactory(JSON_FACTORY) 
      .setTransport(TRANSPORT) 
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET).build() 
      .setFromTokenResponse(tokenResponse); 

我刪除執行the requisite checks discussed in this thread爲了簡單的線條。

 // Store the token in the session for later use. 
     request.session().attribute("token", tokenResponse.toString()); 

值得注意這裏,你想,除非用戶斷開你的應用程序來保存這些憑證。該示例正在使用會話,因爲在生產環境中,會話可以由數據庫支持並在服務器重新啓動後恢復。

在您具有訪問/刷新令牌和到期時間後,爲OAuth v2令牌構建憑據,然後該庫將適當地在內部刷新訪問令牌。下面的代碼顯示了這是如何在快速啓動從用戶的會話中檢索令牌數據完成,還包括由客戶端進行的API調用,證明服務器的Java客戶端工作:

 // Build credential from stored token data. 
     GoogleCredential credential = new GoogleCredential.Builder() 
      .setJsonFactory(JSON_FACTORY) 
      .setTransport(TRANSPORT) 
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET).build() 
      .setFromTokenResponse(JSON_FACTORY.fromString(
       tokenData, GoogleTokenResponse.class)); 
     // Create a new authorized API client. 
     Plus service = new Plus.Builder(TRANSPORT, JSON_FACTORY, credential) 
      .setApplicationName(APPLICATION_NAME) 
      .build(); 
     // Get a list of people that this user has shared with this app. 
     PeopleFeed people = service.people().list("me", "visible").execute(); 

如果你想以不同方式執行此操作,則可以在構造Plus服務對象之前,從訪問令牌,刷新令牌等中顯式構造tokenData對象。

+0

感謝您的快速回復。我正在使用另一個庫,我使用了你提供的那個,它對我有用:) – 2013-03-25 18:55:03

+0

我想問另一個問題,我可以在Google Plus上獲得用戶流或新聞源嗎?或者API只提供訪問用戶自己的帖子? – 2013-03-25 18:56:14

+0

您應該查看activities.list,https://developers.google.com/+/api/latest/activities/list,瞭解公共活動數據。隨時也可以開始另一個問題。 – class 2013-03-29 04:05:08