【问题标题】:How to successfully run "Java Quickstart" sample for Google Drive API?如何成功运行 Google Drive API 的“Java 快速入门”示例?
【发布时间】:2017-04-10 05:56:39
【问题描述】:

我按照 Google 的 Java Quickstart 指南尝试开发 Google Drive 文件的搜索功能。在我执行gradle -q run 或gradle run 命令后,它会打开一个网页并显示“错误:redirect_uri_mismatch”消息。

错误消息:

代码如下:

package main.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.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
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.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

public class Quickstart {
    /** Application name. */
    private static final String APPLICATION_NAME = "Drive API Java Quickstart";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
            ".credentials/drive-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    /**
     * Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials at
     * ~/.credentials/drive-java-quickstart
     */
    private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Creates an authorized Credential object.
     * 
     * @return an authorized Credential object.
     * @throws IOException
     */
    public static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in = Quickstart.class.getResourceAsStream("/client_secret.json");
        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(DATA_STORE_FACTORY).setAccessType("offline").build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }

    /**
     * Build and return an authorized Drive client service.
     * 
     * @return an authorized Drive client service
     * @throws IOException
     */
    public static Drive getDriveService() throws IOException {
        Credential credential = authorize();
        return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static void main(String[] args) throws IOException {
        // Build a new authorized API client service.
        Drive service = getDriveService();

        // Print the names and IDs for up to 10 files.
        FileList result = service.files().list().setPageSize(10).setFields("nextPageToken, files(id, name)").execute();
        List<File> files = result.getFiles();
        if (files == null || files.size() == 0) {
            System.out.println("No files found.");
        } else {
            System.out.println("Files:");
            for (File file : files) {
                System.out.printf("%s (%s)\n", file.getName(), file.getId());
            }
        }
    }
}

开发环境:

build.gradle 文件:

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'Quickstart'
sourceCompatibility = 1.7
targetCompatibility = 1.7
version = '1.0'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.api-client:google-api-client:1.22.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.22.0'
    compile 'com.google.apis:google-api-services-drive:v3-rev68-1.22.0' 
}

我的 Google 开发者控制台:

我应该怎么做才能成功运行gradle -q run 或gradle run 命令? 如何正确配置“Redirect_URI”?

【问题讨论】:

    标签: java google-drive-api google-oauth google-api-java-client


    【解决方案1】:

    基于此thread,如果您使用Gradle Wrapper(Android Studio 中的推荐选项),您可以通过在项目根文件夹(其中@ 987654326@ 文件是)。如果您不使用 gradle 包装器,则使用 gradle compileDebug --stacktrace 代替(大概)。这样,您就可以知道错误的根源。

    您实际上并不需要使用--stacktrace 运行,但从命令行单独运行gradlew compileDebug 应该会告诉您错误在哪里。

    您也可以通过转到以下菜单项来try cleaning your project:Project &gt; Clean... 如果这不起作用,请尝试从构建路径中删除 jar 并重新添加它们。

    补充:

    如何正确配置“Redirect_URI”?

    您可以查看这个 SO 线程:How to set redirect_uri in google developer console?。

    重定向 URI 是一个仅由进行 oAuth2 身份验证的 Web 应用程序使用的对象;因此,当您创建一个新的客户端 ID 时,选择“Web 应用程序”作为 ID 类型,将出现一个文本区域,您可以在其中输入所有允许的重定向 URI(这些网页将由您编码,并且需要执行oauth2票据验证的功能)。

    如果您的应用不是网络应用,则选择“已安装的应用”作为类型,您将获得可在 Android/iOS/桌面应用中使用的密钥。但是,此密钥在 Web 应用程序中根本不可用。

    如果您的网络应用程序不需要写入任何数据或上传任何文件,您可以创建一个公共 API 密钥,您只需将其作为参数包含在您的请求中。

    服务帐户(您在上图中显示)与 YouTube API 不兼容。

    【讨论】:

    • 嗨@abielita,我有一个进展并更新了问题。 PTAL。你知道如何配置“redirect_URI”吗?
    • 感谢@abielita。我找到了解决方案!我应该将“应用程序类型”选择为“其他”而不是“Web 应用程序”。
    • @Jack 谢谢你的评论很有帮助。我遇到了同样的错误,将应用程序类型更改为“其他”后,它解决了问题。但我发现几乎没有提到这一点。谢谢顺便说一句!:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多