如何成功运行Google Drive API的“Java Quickstart”示例?

时间:2017-04-10 05:56:39

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

我按照Google的Java Quickstart指南尝试为Google云端硬盘文件开发搜索功能。执行gradle -q rungradle run命令后,它会打开一个网页并显示“Error: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 Developer Console:

如何成功运行gradle -q rungradle run命令? 如何正确配置“Redirect_URI”?

1 个答案:

答案 0 :(得分:1)

基于此thread,如果您使用的是Gradle Wrapper(Android Studio中推荐的选项),则可以通过从根文件夹中的命令行运行gradlew compileDebug --stacktrace来启用堆栈跟踪。您的项目(gradlew文件所在的位置)。如果您没有使用gradle包装器,则使用gradle compileDebug --stacktrace代替(大概)。有了这个,您就可以知道错误的根源。

  

您真的不需要使用--stacktrace运行,但是,从命令行运行gradlew compileDebug,应该告诉您错误的位置。

您也可以try cleaning your project转到以下菜单项:Project > Clean...如果这不起作用,请尝试从构建路径中删除jar并再次添加。

其他:

如何正确配置&#34; Redirect_URI&#34;?

您可以查看此SO帖子:How to set redirect_uri in google developer console?

  

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

     

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

     

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

     

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