获取Google Drive API的OAuth凭据

时间:2014-09-17 07:41:10

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

我正试图通过我正在开发的应用程序访问谷歌驱动器上的一些文件。不幸的是,我在获取凭证方面遇到了困难。我创建了一个Google服务帐户,提供的电子邮件地址和私钥应该没问题。 但是,当从下面调用方法getDriveService()时,我收到错误

java.lang.NullPointerException
    at java.util.Collections$UnmodifiableCollection.<init>(Unknown Source)
    at java.util.Collections.unmodifiableCollection(Unknown Source)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.<init>(GoogleCredential.java:321)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.build(GoogleCredential.java:515)

我在这里做了一些明显的错误吗?

到目前为止我的代码:

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
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.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;

import java.security.GeneralSecurityException;
import java.io.IOException;
import java.net.URISyntaxException;

private static final String SERVICE_ACCOUNT_EMAIL = "VERY_LONG_ID@developer.gserviceaccount.com";
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/home/user/googledriveKey.p12";

public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountPrivateKeyFromP12File(
            new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
        .build();
    Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
        .setHttpRequestInitializer(credential).build();
    return service;
}

1 个答案:

答案 0 :(得分:3)

文档清楚地显示了如何获取凭据(这是您已经拥有的):

GoogleCredential credential = new GoogleCredential.Builder()
   .setTransport(httpTransport)
   .setJsonFactory(jsonFactory)
   .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
   .setServiceAccountScopes(DriveScopes.DRIVE)
   .setServiceAccountPrivateKeyFromP12File(
       new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
   .build();

来源:https://developers.google.com/drive/web/service-accounts

如果您想从个人用户的Google云端硬盘访问数据,您还需要致电

   .setServiceAccountUser(userEmail)

来源:https://developers.google.com/drive/web/delegation#instantiate_a_drive_service_object