使用gmailQuickStart时无法获取Google API令牌

问题描述

我已经从https://developers.google.com/gmail/api/quickstart/java下载了gmail快速入门演示。

我已经在Google Cloud Platform中注册,并加入了gmail api,创建了自己的项目和凭据...

当我全力以赴时,一切都会朝着正确的方向前进。下一秒,我陷入了麻烦。

第一次,我运行的是原始程序,如提供的网站一样。


    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    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;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.security.GeneralSecurityException;
    import java.util.Collections;
    import java.util.List;
    
    public class GmailQuickstart {
        private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
        private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
        /**
         * Global instance of the scopes required by this quickstart.
         * If modifying these scopes,delete your previously saved tokens/ folder.
         */
        private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
        private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
        /**
         * Creates an authorized Credential object.
         * @param HTTP_TRANSPORT The network HTTP Transport.
         * @return An authorized Credential object.
         * @throws IOException If the credentials.json file cannot be found.
         */
        private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
            // Load client secrets.
            InputStream in = GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
            if (in == null) {
                throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
            }
            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(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                    .setAccessType("offline")
                    .build();
            LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
            return new AuthorizationCodeInstalledApp(flow,receiver).authorize("user");
        }
    
        public static void main(String... args) throws IOException,GeneralSecurityException {
            // Build a new authorized API client service.
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            Gmail service = new Gmail.Builder(HTTP_TRANSPORT,getCredentials(HTTP_TRANSPORT))
                    .setApplicationName(APPLICATION_NAME)
                    .build();
    
            // Print the labels in the user's account.
            String user = "me";
            ListLabelsResponse listResponse = service.users().labels().list(user).execute();
            List<Label> labels = listResponse.getLabels();
            if (labels.isEmpty()) {
                System.out.println("No labels found.");
            } else {
                System.out.println("Labels:");
                for (Label label : labels) {
                    System.out.printf("- %s\n",label.getName());
                }
            }
        }
    }

及其相关性如下:


    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.5.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <groupId>com.demo</groupId>
        <artifactId>gmail.demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>gmail-demo</name>
        <packaging>jar</packaging>
        <description>Gmail Demo</description>
    
        <properties>
            <parent.version>0.0.1-SNAPSHOT</parent.version>
            <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>com.google.api-client</groupId>
                <artifactId>google-api-client</artifactId>
                <version>1.30.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
            <dependency>
                <groupId>com.google.oauth-client</groupId>
                <artifactId>google-oauth-client-jetty</artifactId>
                <version>1.31.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-gmail -->
            <dependency>
                <groupId>com.google.apis</groupId>
                <artifactId>google-api-services-gmail</artifactId>
                <version>v1-rev110-1.25.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
        </dependencies>
    
    </project>

那我就有了


    Exception in thread "main" javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:994)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1340)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1315)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:264)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:108)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:79)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:995)
        at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:322)
        at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:158)
        at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:79)
        at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:127)
        at GmailQuickstart.getCredentials(GmailQuickstart.java:57)
        at GmailQuickstart.main(GmailQuickstart.java:63)
    Caused by: java.io.EOFException: SSL peer shut down incorrectly
        at sun.security.ssl.InputRecord.read(InputRecord.java:505)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
        ... 17 more

在谷歌搜索和谷歌搜索之后,我发现这可能是代理问题。然后,我按如下所示重写程序,添加了代理配置。


    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.GoogleUtils;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.javanet.ConnectionFactory;
    import com.google.api.client.http.javanet.NetHttpTransport;
    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;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import java.net.URL;
    import java.security.GeneralSecurityException;
    import java.util.Collections;
    import java.util.List;
    
    public class GmailQuickstart3 {
        private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
        private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
        /**
         * Global instance of the scopes required by this quickstart.
         * If modifying these scopes,GeneralSecurityException {
            // Build a new authorized API client service.
            System.out.println(System.getProperties());
    
            final NetHttpTransport HTTP_TRANSPORT =
                    (new NetHttpTransport.Builder())
                            .trustCertificates(GoogleUtils.getCertificateTrustStore())
                            .setProxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("******",30900)))
    //                         .setConnectionFactory(connectionFactory)
                            .build();
            Gmail service = new Gmail.Builder(HTTP_TRANSPORT,getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME).build();
    
            // Print the labels in the user's account.
            String user = "me";
            ListLabelsResponse listResponse = service.users().labels().list(user).execute();
            List<Label> labels = listResponse.getLabels();
            if (labels.isEmpty()) {
                System.out.println("No labels found.");
            } else {
                System.out.println("Labels:");
                for (Label label : labels) {
                    System.out.printf("- %s\n",label.getName());
                }
            }
        }
    }
    ```
    Then I have got
    ```
    Please open the following address in your browser:
      https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=2467719584-um6onu5chc8hmn00is5j3ctl6g2mvvru.apps.googleusercontent.com&redirect_uri=http://localhost:8888/Callback&response_type=code&scope=https://www.googleapis.com/auth/gmail.labels
    Attempting to open that address in the default browser now...
    Exception in thread "main" java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 301 Moved Permanently"
        at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:2152)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:183)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1340)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1315)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:264)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:108)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:79)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:995)
        at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:322)
        at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:158)
        at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:79)
        at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:127)
        at GmailQuickstart3.getCredentials(GmailQuickstart3.java:63)
        at GmailQuickstart3.main(GmailQuickstart3.java:88)

CONNECT oauth2.googleapis.com:443 HTTP/1.1
User-Agent: Java/1.8.0_231
Host: oauth2.googleapis.com
Accept: text/html,image/gif,image/jpeg,*; q=.2,*/*; q=.2
Proxy-Connection: keep-alive

HTTP/1.1 301 Moved Permanently
Content-length: 0
Location: https://oauth2.googleapis.com/

有人可以帮助我解决吗? 我真的很困惑,问题已经持续了几天,而且我还没有找到任何有用的文档。

分级运行结果:(于2020年10月9日添加)

PS D:\xnj\workspace\gmailQuickstart> gradle run

> Task :run
十月 09,2020 11:07:16 下午 com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
警告: unable to change permissions for everybody: D:\xnj\workspace\gmailQuickstart\tokens IDLE
十月 09,2020 11:07:16 下午 com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
警告: unable to change permissions for owner: D:\xnj\workspace\gmailQuickstart\tokens
2020-10-09 23:07:16.074:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2020-10-09 23:07:16.075:INFO::jetty-6.1.26
2020-10-09 23:07:16.088:INFO::Started SocketConnector@localhost:8888
Please open the following address in your browser:
  https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=2467719584-um6onu5chc8hmn00is5j3ctl6g2mvvru.apps.googleusercontent.com&redirect_uri=http://localhost:8888/Callback&response_type=code&scope=https://www.googleapis.com/auth/gmail.labels
Attempting to open that address in the default browser now...
2020-10-09 23:08:54.694:INFO::Stopped SocketConnector@localhost:8888
Exception in thread "main" java.net.SocketTimeoutException: connect timed out
        at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:673)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
        at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
        at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:259)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:77)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
        at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:283)
        at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:158)
        at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:79)
        at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:84)
        at GmailQuickstart.getCredentials(GmailQuickstart.java:57)
        at GmailQuickstart.main(GmailQuickstart.java:63)

> Task :run FAILED

在单击控制台中的url之前,控制台日志将挂起“正在尝试在默认浏览器中立即打开该地址...”,如果我什么也不做,它将保持原样。当我单击该URL时,控制台将立即打印错误跟踪,并告诉我套接字“连接超时”

timeout-picture

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)