连接谷歌日历服务java

时间:2017-10-18 10:54:30

标签: java google-calendar-api

我想使用Google Calendar Api在java中创建一个应用程序,但我尝试连接到api服务,但这是错误的。 这是我的代码(使用Eclipse)

 GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport())

              .setServiceAccountId("*****************")
    //    .setServiceAccountUser("my e-mail adress")
              .setClientSecrets("","********")
        //    .setServiceAccountScopes(CalendarScopes.CALENDAR)
              .setJsonFactory(new GsonFactory())

              .build();
            Calendar  client = new com.google.api.services.calendar.Calendar.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(), new GsonFactory(), credential).build();

错误是:

Exception in thread "main" java.lang.IllegalArgumentException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
    at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.<init>(GoogleCredential.java:323)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.build(GoogleCredential.java:539)
    at google_calendar.add_evenement.main(add_evenement.java:21)

1 个答案:

答案 0 :(得分:0)

如果您还没有这样做,请检查Using OAuth 2.0 for Server to Server Applications

如上所述,如果您已授予对服务帐户的域范围访问权限并且您要模拟用户帐户,请使用setServiceAccountUser GoogleCredential方法指定用户帐户的电子邮件地址厂。例如:

GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(httpTransport)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId(emailAddress)
    .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
    .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
    .setServiceAccountUser("user@example.com")
    .build();

然后,calling Google APIs使用Java:

  

使用GoogleCredential对象通过完成以下步骤来调用Google API:

     
      
  1. 使用GoogleCredential对象为要调用的API创建服务对象。例如:
  2.   
SQLAdmin sqladmin =
    new SQLAdmin.Builder(httpTransport, JSON_FACTORY, credential).build();
  
      
  1. 使用interface provided by the service object向API服务发出请求。例如,要在令人兴奋的示例-123项目中列出Cloud SQL数据库的实例:
  2.   
SQLAdmin.Instances.List instances =
    sqladmin.instances().list("exciting-example-123").execute();