在具有服务帐户的google drive api中,访问令牌和刷新令牌为空

时间:2017-04-10 05:23:41

标签: java google-app-engine google-drive-api service-accounts

我运行代码时获取访问令牌并刷新令牌为null。没有编译错误。我不明白为什么会这样。请帮助。

我在官方网站提供的示例中关注此示例。

实际上,我想进行服务器到服务器的授权,可以使用谷歌驱动器上的服务帐户来完成。我甚至不想向用户显示同意屏幕。我正在关注位于

的google驱动器文档

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

我的代码是:

public class TFT {

private static final String ApplicationName = "Boston";
private static final String serviceAccountEmailAddress = "boss@boston-163913.iam.gserviceaccount.com";
private static final String serviceAccountUser = "abc.pqr@yopmail.com";

private static List<File> retrieveAllFiles(Drive service) throws IOException {
    List<File> result = new ArrayList<>();
    Files.List request = service.files().list();

    do {
        FileList files = request.execute();

        result.addAll(files.getFiles());

        request.setPageToken(files.getNextPageToken());

    } while (request.getPageToken() != null && request.getPageToken().length() > 0);
    return result;
}

public static Drive getDriveService() throws IOException {

    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    GoogleCredential credential = null;

    try {
        credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(serviceAccountEmailAddress)
                .setServiceAccountScopes(DriveScopes.all())
                .setServiceAccountUser(serviceAccountUser)
                .setServiceAccountPrivateKeyFromP12File(new java.io.File("/home/xpointers/Downloads/Boston-2b55ddf4a5c8.p12"))
                .build();

    } catch (GeneralSecurityException | IOException e) {
        e.printStackTrace();
    }

    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(ApplicationName)
            .build();
    return service;
}

private java.io.File getp12File(String fileName) {


    ClassLoader classLoader = getClass().getClassLoader();
    return new java.io.File(classLoader.getResource(fileName).getFile());

}

public static void main(String[] args) {

    try {

        Drive service = getDriveService();

        List<File> files;

        files = retrieveAllFiles(service);

        System.out.println(files);

    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

1 个答案:

答案 0 :(得分:0)

您可以参考此thread,建议使用credential.refreshToken();

  

我们需要致电credential.refreshToken();
   然后
   String token=credential.getAccessToken();

参考文献: