2012-05-31 142 views
1
import com.google.api.client.http.HttpRequestFactory; 
import com.google.api.client.http.HttpResponseException; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson.JacksonFactory; 
import com.google.api.client.util.DateTime; 
//import com.google.api.services.calendar.Calendar; 
import com.google.api.services.calendar.model.Calendar; 
import com.google.api.services.calendar.model.Event; 
import com.google.api.services.calendar.model.EventAttendee; 
import com.google.api.services.calendar.model.EventDateTime; 
import com.google.api.client.googleapis.services.GoogleClient.Builder; 
//import com.google.api.services.calendar.Calendar.Calendars; 
//import com.google.api.services.calendar.Calendar.Calendars.Insert; 
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; 
import com.google.api.client.auth.oauth2.draft10.AccessProtectedResource.Method; 
import com.google.api.client.auth.oauth2.draft10.AccessTokenErrorResponse; 
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant; 
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource; 
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.security.GeneralSecurityException; 
import java.util.ArrayList; 
import java.util.Arrays; 

@SuppressWarnings({ "deprecation", "unused" }) 
public class connect{ 

    public void setUp() throws IOException { 

     HttpTransport httpTransport = new NetHttpTransport(); 
     JacksonFactory jsonFactory = new JacksonFactory(); 

     // The clientId and clientSecret are copied from the API Access tab on 
     // the Google APIs Console 
     String clientId = "MYCLIENTID"; 
     String clientSecret = "CLIENTSECRET"; 

     // Or your redirect URL for web based applications. 
     String redirectUrl = "urn:ietf:wg:oauth:2.0:oob"; 
     String scope = "https://www.googleapis.com/auth/calendar"; 

     // Step 1: Autorizzazione --> 
     String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope) 
      .build(); 

     // Point or redirect your user to the authorizationUrl. 
     System.out.println("Vai al seguente indirizzo nel browser:"); 
     System.out.println(authorizationUrl); 

     // Read the authorization code from the standard input stream. 
     System.out.println("Qual e' il tuo codice di autorizzazione?"); 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     String code = in.readLine(); 

     // Fine Step 1 <-- 
     // Step 2: Scambio --> 
     AccessTokenResponse authResponse = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory, 
       clientId, clientSecret, code, redirectUrl).execute(); 
     System.out.println("Scrivi: "+authResponse); 
     System.out.println("Token d'accesso: "+authResponse.accessToken); 
     if(scope == "https://www.googleapis.com/auth/calendar") 
     System.out.println("Scope di lettura e scrittura usato :"+scope); 
     else 
      System.out.println("Scope di sola lettura usato :"+scope); 
     // Fine Step 2 <-- 

     GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
       authResponse.accessToken, httpTransport, jsonFactory, clientId, clientSecret, 
       authResponse.refreshToken); 
     System.out.println("Il Client ID utilizzato e': "+accessProtectedResource.getClientId()); 
     System.out.println("Il Secret ID utilizzato e': "+accessProtectedResource.getClientSecret()); 
     System.out.println("L'url di autenticazione e': "+accessProtectedResource.getAuthorizationServerUrl()); 

     com.google.api.services.calendar.Calendar service = new com.google.api.services.calendar.Calendar(httpTransport, jsonFactory); 
     Calendar cale = new Calendar(); 

     System.out.println("Menu'"); 
     System.out.println("Cosa desideri fare?"); 
     System.out.println("1) Creare un calendario"); 
     System.out.println("2) Creare un evento"); 
     System.out.println("3) Eliminare un calendario"); 
     System.out.println("0) Uscita"); 

     int scelta = Integer.parseInt(in.readLine()); 
     System.out.println(scelta); 
     switch(scelta){ 
     case 1: 
      //insert calendar 
      Calendar ClaudioCal = new Calendar(); 
      ClaudioCal.setSummary("Esempio di calendario di Claudio"); 
      ClaudioCal.setTimeZone("America/Los_Angeles"); 

      cale = service.calendars().insert(ClaudioCal).execute(); 
      break; 

      //other case....... 

     System.out.println("Fatto"); 
    } 
    } 

嗨,這是我的代碼連接到谷歌帳戶來修改日曆,但每次系統響應我「未經授權」。像作爲的accessToken沒有被證實,我不明白的地方的問題與Oauth 2.0連接谷歌日曆

請幫我 感謝很多提前

+0

請提供有關發生的事情的分步信息。你什麼時候得到未經授權的例外?什麼是堆棧跟蹤? HTTP響應正文中是否有信息會告訴您有關錯誤原因的更多信息?您是否在您的項目的Google API控制檯中啓用了日曆API?等等。 –

+0

日曆apis已啓用,此時 System.out.println(authorizationUrl);我瀏覽它,比我點擊允許訪問我的progett和代碼設備。我將它複製到我的程序中String code = in.readLine();比當我設置在我的菜單中創建日曆'時,在這一點上cale = service.calendars()。insert(ClaudioCal).execute();該程序失敗,未經授權的異常...它似乎像我的程序不驗證代碼與accessToken – marzobryant90

回答

1

在最新版本的Java API庫中,用於處理OAuth的機制發生了顯着變化。

你要遵循示例代碼此處引用生成器模式: http://code.google.com/p/google-api-java-client/source/browse/calendar-cmdline-sample/src/main/java/com/google/api/services/samples/calendar/cmdline/CalendarSample.java?repo=samples#57

Credential credential = OAuth2Native.authorize(
    HTTP_TRANSPORT, JSON_FACTORY, new LocalServerReceiver(), 
    Arrays.asList(CalendarScopes.CALENDAR)); 

// set up global Calendar instance 
client = com.google.api.services.calendar.Calendar.builder(HTTP_TRANSPORT, JSON_FACTORY) 
    .setApplicationName("Google-CalendarSample/1.0").setHttpRequestInitializer(credential) 
    .build(); 

這會自動處理提示您(甚至不會在桌面上一些偉大的魔法打開瀏覽器)。或者,如果您正在尋找如何在封底下執行此操作,請在此處提供更多信息: http://code.google.com/p/google-api-java-client/source/browse/shared/shared-sample-cmdline/src/main/java/com/google/api/services/samples/shared/cmdline/oauth2/OAuth2Native.java?repo=samples#102

+0

當核心轉到類Oauth2Native的loadClientSecret時,它會正確加載客戶端ID和客戶端密鑰,但是當他使用變量clientSecrets執行GoogleAuthorizationCodeFlow.Builder()時,它會失敗,如果我設置爲GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder ( transport,jsonFactory,「clientId」,「clientSecret」,作用域).build();一切工作順利。爲什麼在使用clientSecrets失敗之前失敗? (clientSecrets是GoogleClientSecrets對象)也Preconditions.checkArgument方法失敗,因爲他嘗試評估文件的錯誤條件 – marzobryant90

0

後您設置您的GoogleAccessProtectedResource對象,你不會傳遞到日曆服務類正確。

更改此:

com.google.api.services.calendar.Calendar service = 
    new com.google.api.services.calendar.Calendar(httpTransport, 
                jsonFactory); 

這樣:

com.google.api.services.calendar.Calendar service = 
    new com.google.api.services.calendar.Calendar(httpTransport, 
                accessProtectedResource, 
                jsonFactory); 

應該這樣做。

+0

構造函數Calendar(HttpTransport,GoogleAccessProtectedResource,JacksonFactory)未定義 – marzobryant90

+0

我有這些導入導入com.google.api.services.calendar 。日曆; // import com.google.api.services.calendar.model.Calendar; // import com.google.api.services.calendar.Calendar.Calendars; – marzobryant90

+0

因此,看起來OAuth的處理方式完全隨着庫的最新版本而改變。我會用最新的圖書館以最新的方式再次回答。 –