Gmail API';s的Java集成问题

Gmail API';s的Java集成问题,java,google-oauth,gmail-api,google-api-java-client,Java,Google Oauth,Gmail Api,Google Api Java Client,我参与了一个开发项目,该项目使我将Gmail API集成到我的Java项目中 和所有人一样,我开始了测试,带来了官方文档中提供的示例 我对它进行了一些测试,但我无法登录并列出我帐户的标签 这是我的班级: import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import co

我参与了一个开发项目,该项目使我将Gmail API集成到我的Java项目中

和所有人一样,我开始了测试,带来了官方文档中提供的示例

我对它进行了一些测试,但我无法登录并列出我帐户的标签

这是我的班级:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;

public class ComunicoTestSergio {

    private static HttpTransport HTTP_TRANSPORT;
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/ComunicoTestSergio.json");
    private static FileDataStoreFactory DATA_STORE_FACTORY;
    private static final String APPLICATION_NAME ="comunico";

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }
    public static Credential authorize() throws IOException {
        InputStream is = ComunicoTestSergio.class.getResourceAsStream(
                "/comunico-test-sergio-client_secret_113926736970383780927.json");
        InputStreamReader isr = new InputStreamReader(is);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);           
        Credential credential = new GoogleCredential.Builder()
                .setTransport( HTTP_TRANSPORT )
                .setJsonFactory( JSON_FACTORY )
                .setServiceAccountId( "comunico-test-sergio comunico-test-sergio@comunico-1266.iam.gserviceaccount.com" ) 
                .setServiceAccountScopes( Arrays.asList(GmailScopes.GMAIL_LABELS) )
                .setServiceAccountUser( "otticanet.ad@gmail.com" )
                .setClientSecrets( clientSecrets )
                .build();
        return credential;
    }
    public static Gmail getGmailService() throws Exception {
        Credential credential = authorize();
        return new Gmail.Builder( HTTP_TRANSPORT, JSON_FACTORY, credential )
                .setApplicationName( APPLICATION_NAME )
                .build();
    }

    public static void main(String[] args) {
        try {
            Gmail service = getGmailService();
            String user = "me";
            ListLabelsResponse listResponse =service.users().labels().list(user).execute();
            List<Label> labels = listResponse.getLabels();
            if (labels.size() == 0) { System.out.println("No labels found."); } 
            else {
                System.out.println("Labels:");
                for (Label label : labels) {
                    System.out.printf("- %s\n", label.getName());
                }
            }
        } catch ( Exception ex ) {
            ex.printStackTrace();
        }
    }
}
这是我的JSON凭证文件(从Google开发者控制台下载):

怎么了?!我循序渐进地学习在线教程…:(


在您开始使用服务帐户之前,非常感谢您提供的所有帮助。

这里有几个问题

  • 这个应用程序只会访问你的gmail帐户还是访问很多用户
  • 这些用户如何授权此应用程序? 2a.如果应用程序由公司使用,则管理员可以授权一组用户。 2b.如果应用程序由个人用户使用,则他们应通过Oauth审批流对其进行授权
  • 在您的示例中,您创建了一个服务帐户,并试图访问otticanet的电子邮件。ad@gmail.com.otticanet是怎么做到的。ad@gmail.com授权服务帐户授予访问权限?它可能没有。
    对于2a,服务帐户更有意义。对于2b,您应该通过oauth审批流获取用户,获取代码并将其交换为刷新/访问令牌,并将其用于API。

    您的Json文件看起来像Oauth2凭据。您的代码显示为服务帐户。您在Google开发者控制台上创建了什么,您应该做什么创建了吗?你能添加一个链接到你正在学习的教程吗?我发现Gmail quick start for java不包含你的服务帐户代码。嗨,DalmTo,我学习了一些在线教程:1)2)3)4)ant这是正确的库集:JSON凭据是OAuth 2.0客户端ID,但我也注册了一个服务帐户密钥。。。
    <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-gmail</artifactId>
          <version>v1-rev40-1.21.0</version>
        </dependency>
      </dependencies>
    
    /home/sbelli/.m2/repository/com/google/apis/google-api-services-gmail/v1-rev40-1.21.0/google-api-services-gmail-v1-rev40-1.21.0.jar
    /home/sbelli/.m2/repository/com/google/api-client/google-api-client/1.21.0/google-api-client-1.21.0.jar
    /home/sbelli/.m2/repository/com/google/oauth-client/google-oauth-client/1.21.0/google-oauth-client-1.21.0.jar
    /home/sbelli/.m2/repository/com/google/http-client/google-http-client/1.21.0/google-http-client-1.21.0.jar
    /home/sbelli/.m2/repository/org/apache/httpcomponents/httpclient/4.0.1/httpclient-4.0.1.jar
    /home/sbelli/.m2/repository/org/apache/httpcomponents/httpcore/4.0.1/httpcore-4.0.1.jar
    /home/sbelli/.m2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar
    /home/sbelli/.m2/repository/commons-codec/commons-codec/1.3/commons-codec-1.3.jar
    /home/sbelli/.m2/repository/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar
    /home/sbelli/.m2/repository/com/google/http-client/google-http-client-jackson2/1.21.0/google-http-client-jackson2-1.21.0.jar
    /home/sbelli/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.1.3/jackson-core-2.1.3.jar
    /home/sbelli/.m2/repository/com/google/guava/guava-jdk5/17.0/guava-jdk5-17.0.jar
    
    { "installed":{ "client_id":"my_client_id_x", "project_id":"my_project_id", "auth_uri":"https://accounts.google.com/o/oauth2/auth", "token_uri":"https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs" } }
    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:317)
        at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.build(GoogleCredential.java:515)
        at it.trew.comunico.business.test.ComunicoTestSergio.authorize(ComunicoTestSergio.java:51)
        at it.trew.comunico.business.test.ComunicoTestSergio.getGmailService(ComunicoTestSergio.java:55)
        at it.trew.comunico.business.test.ComunicoTestSergio.main(ComunicoTestSergio.java:63)
    
    com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
    {
      "code" : 401,
      "errors" : [ {
        "domain" : "global",
        "location" : "Authorization",
        "locationType" : "header",
        "message" : "Login Required",
        "reason" : "required"
      } ],
      "message" : "Login Required"
    }
        at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at it.trew.comunico.business.test.ComunicoTestSergio.main(ComunicoTestSergio.java:65)
    
               .setServiceAccountId( "comunico-test-sergio comunico-test-sergio@comunico-1266.iam.gserviceaccount.com" ) 
                .setServiceAccountScopes( Arrays.asList(GmailScopes.GMAIL_LABELS) )
                .setServiceAccountUser( "otticanet.ad@gmail.com" )