构建Google Drive API文件上传时出现问题

时间:2017-11-17 14:14:43

标签: android google-drive-api

我正在尝试构建一个Android应用,允许我根据用户的要求将文件上传到Google云端硬盘。但是,我无法在任何地方找到一个单一的工作示例。这里和那里散布着一半的烤片。其中一些能够通过OAuth连接,其他人能够创建一个空文件或文件夹,但我无处可找到一个保存令牌的应用程序,并无缝上传文件。我对如何实现功能毫无头绪,因为没有书籍或视频可用,谷歌自己的样本对我不起作用。我正在努力使代码工作。请帮助别人。感谢。

1 个答案:

答案 0 :(得分:0)

我总是使用下面的课程来创建Google云端硬盘服务。

首先,您需要在pom文件中包含这些依赖项:

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v2-rev282-1.23.0</version>
</dependency>

然后使用此类创建驱动器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.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 java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author jalal-sordo
 */
public class GoogleDriveServiceFactory {

    private String applicationName;

    private JsonFactory jsonFactory;
    private HttpTransport googleDriveHttpTransport;
    private List<String> googleDriveApiScopes;
    private String googleDriveClientSecretFilePath;
    private FileDataStoreFactory credentialsStoreFolder;

    public GoogleDriveServiceFactory(ApplicationParameters params) {
        try {
            this.googleDriveClientSecretFilePath = params.getGoogleDriveClientSecretFilePath();
            //  = new FileInputStream(googleDriveClientSecretFilePath);
            applicationName = "someApplicationName";
            jsonFactory = JacksonFactory.getDefaultInstance();
            googleDriveApiScopes = Arrays.asList(DriveScopes.DRIVE);
            googleDriveHttpTransport = GoogleNetHttpTransport.newTrustedTransport();
            java.io.File googleDriveCredentialsStore = new java.io.File(params.getGoogleDriveCredentialsFolderPath());
            credentialsStoreFolder = new FileDataStoreFactory(googleDriveCredentialsStore);
        } catch (IOException | GeneralSecurityException t) {
            System.err.println(t.getMessage());
            System.exit(1);
        }
    }

    public Credential authorize() throws IOException {
        InputStreamReader streamReader = new FileReader(new java.io.File(googleDriveClientSecretFilePath));
        GoogleClientSecrets clientSecrets
                = GoogleClientSecrets.load(jsonFactory, streamReader);
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow
                = new GoogleAuthorizationCodeFlow.Builder(
                        googleDriveHttpTransport, jsonFactory, clientSecrets, googleDriveApiScopes)
                        .setDataStoreFactory(credentialsStoreFolder)
                        .setAccessType("offline")
                        .build();
        Credential credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");

        return credential;
    }

    public Drive getDriveService() throws IOException {
        Credential credential = authorize();
        return new Drive.Builder(
                googleDriveHttpTransport, jsonFactory, credential)
                .setApplicationName(applicationName)
                .build();
    }
}

您还需要此类为上面的类提供参数:

/**
 *
 * @author jalal-sordo
 */
public class ApplicationParameters {

    private String googleDriveCredentialsFolderPath;
    private String googleDriveClientSecretFilePath;

    public String getGoogleDriveCredentialsFolderPath() {
        return googleDriveCredentialsFolderPath;
    }

    public void setGoogleDriveCredentialsFolderPath(String googleDriveCredentialsFolderPath) {
        this.googleDriveCredentialsFolderPath = googleDriveCredentialsFolderPath;
    }

    public String getGoogleDriveClientSecretFilePath() {
        return googleDriveClientSecretFilePath;
    }

    public void setGoogleDriveClientSecretFilePath(String googleDriveClientSecretFilePath) {
        this.googleDriveClientSecretFilePath = googleDriveClientSecretFilePath;
    }

    @Override
    public String toString() {
        return "ApplicationParameters{"
                + "\ngoogleDriveCredentialsFolderPath = " + googleDriveCredentialsFolderPath
                + "\ngoogleDriveClientSecretFilePath = " + googleDriveClientSecretFilePath
               + "\n}";
    }

}

这就是您可以创建GoogleDriveServiceFactory实例并执行文件上传的方法:

ApplicationParameters params = new ApplicationParameters();
//this is where you specify where you want the credentials to be stored
//after a successful autherization is made from the browser (this code will 
//open the authorization consent page on your default browser).
params.setGoogleDriveCredentialsFolderPath("/path/to/credentials/folder");
//this is the path to your client_id that you downloaded from google cloud
//console credentials page.
params.setGoogleDriveClientSecretFilePath("/path/to/client_id.json");
GoogleDriveServiceFactory  driveFactory = new GoogleDriveServiceFactory (params);

File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveFactory.getDriveService.files().create(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());