关于 android:无法下载我的应用在 Google Drive 上创建的文件,但可以获取该文件的元数据

Unable to download file created by my app on Google Drive, But can get the metadata of that file

我遵循了 google drive sdk 中提到的所有步骤。我在我的设备(android,运行果冻豆)上创建了一个示例应用程序,并且能够将文件上传到驱动器。尝试下载同一个文件时,我能够获取文件 ID、文件标题、文件下载 URL 等元数据,但无法下载内容。我收到 401 Unauthorized 错误。

我的应用 AUTH SCOPE 是 AUTH_TOKEN_TYPE ="oauth2:https://www.googleapis.com/auth/drive.file";

我正在执行以下操作来获取 OAUTH 令牌:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
AccountManager am = AccountManager.get(this);
        Bundle options = new Bundle();
        am.getAuthToken(
                mAccount,                              
                AUTH_TOKEN_TYPE,                        
                options,                                
                this,                                  
                new OnTokenAcquired(),                  
                new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        invadiateToken();                      
                        super.handleMessage(msg);
                    }
                });

基于令牌,这就是我构建 Drive 对象的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Drive buildService(final String AuthToken) {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
    b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {

        @Override
        public void initialize(JsonHttpRequest request) throws IOException {
            DriveRequest driveRequest = (DriveRequest) request;
            driveRequest.setPrettyPrint(true);
            driveRequest.setKey(API_KEY);
            driveRequest.setOauthToken(AuthToken);
        }
    });

    return b.build();
}

我可以使用以下代码上传文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void uploadLocalFileToDrive(Drive service) throws IOException{

        // File's metadata.
        String mimeType ="text/plain";
        File body = new File();
        body.setTitle("myText.txt");
        body.setDescription("sample app by varun");
        body.setMimeType("text/plain");

        // File's content.
        java.io.File fileContent = new java.io.File(mInternalFilePath);
        FileContent mediaContent = new FileContent(mimeType, fileContent);

        service.files().insert(body, mediaContent).execute();

    }

在尝试下载此应用上传的相同文件时,我在以下代码片段

的这一行 HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute() 处收到 401 未经授权的错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void downloadFileFromDrive(Drive service) throws IOException {
        Files.List request;
            request = service.files().list();
            do {
                FileList files = request.execute();
                for(File file:files.getItems()){
                    String fieldId = file.getId();
                    String title = file.getTitle();
                    Log.e("MS","MSV::  Title-->"+title+"  FieldID-->"+fieldId+" DownloadURL-->"+file.getDownloadUrl());
                    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0 ) {
                        GenericUrl url = new GenericUrl(file.getDownloadUrl());
                        HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute();
                        InputStream isd = resp.getContent();
                        Log.e("MS","MSV:: FileOutPutStream--->"+getFilesDir().getAbsolutePath()+"/downloaded.txt");

                    } else {
                        Log.e("MS","MSV:: downloadURL for this file is null");
                    }
                }
                request.setPageToken(files.getNextPageToken());
            } while (request.getPageToken()!=null && request.getPageToken().length()>0);
    }

谁能帮帮我,让我知道我做错了什么???


这是一个已知问题,将随着 Google Play 服务 API 的发布而得到解决。

由于您的应用程序已获得 https://www.googleapis.com/auth/drive.file 范围的授权,并且下载端点不支持 ?key= 查询参数,因此我们的服务器无法知道哪个项目正在发出请求(以确保该应用程序有权读取此文件的内容)。

与此同时,我可以推荐的唯一解决方法是使用广泛的范围:https://www.googleapis.com/auth/drive。请在开发应用程序和等待 Google Play 服务发布时仅使用它。

要详细了解如何在 Android 中使用新的授权 API,您可能会对这 2 个 Google I/O 演讲感兴趣:构建使用 Web API 的 Android 应用程序和
为 Android 编写高效的云端硬盘应用程序


我已经回答了这个问题,以及所有与 Drive on Android 相关的问题,都在这里:

Android 在 Google Drive SDK 中打开和保存文件

在那个答案中,我发布了用于从 Google Drive 下载文件的方法的代码(如果以下代码本身不清楚,请查看我链接到的完整答案。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
    if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
        if (jFolder == null) {
            jFolder = Environment.getExternalStorageDirectory();
            jFolder.mkdirs();
        }
        try {

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(gFile.getDownloadUrl());
            get.setHeader("Authorization","Bearer" + token);
            HttpResponse response = client.execute(get);

            InputStream inputStream = response.getEntity().getContent();
            jFolder.mkdirs();
            java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() +"/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
            FileOutputStream fileStream = new FileOutputStream(jFile);
            byte buffer[] = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0) {
                fileStream.write(buffer, 0, length);
            }
            fileStream.close();
            inputStream.close();
            return jFile;
        } catch (IOException e) {        
            // Handle IOExceptions here...
            return null;
        }
    } else {
        // Handle the case where the file on Google Drive has no length here.
        return null;
    }
}

我认为我们不需要任何访问令牌来下载文件。我遇到了同样的问题,这很有效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
private class DownloadFile extends AsyncTask<Void, Long, Boolean> {

    private com.google.api.services.drive.model.File driveFile;
    private java.io.File file;

    public DownloadFile(File driveFile) {
        this.driveFile = driveFile;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        if (driveFile.getDownloadUrl() != null
                && driveFile.getDownloadUrl().length() > 0) {
            try {
                HttpResponse resp = mDriveService
                        .getRequestFactory()
                        .buildGetRequest(
                                new GenericUrl(driveFile.getDownloadUrl()))
                        .execute();
                OutputStream os = new FileOutputStream(file);
                CopyStream(resp.getContent(), os);
                os.close();

                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        //use the file
    }
}

public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (;;) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {
    }
}