无法下载我的应用在Google云端硬盘上创建的文件,但可以获取该文件的元数据

时间:2012-07-17 11:50:42

标签: android google-drive-api

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

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

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

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对象的方式

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();
}

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

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未经授权的错误

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);
    }

任何人都可以帮助我,让我知道我做错了什么???

3 个答案:

答案 0 :(得分:5)

这是一个已知问题,将通过发布Google Play Services API来解决。

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

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

要详细了解如何在Android中使用新的授权API,您可能会对这两个Google I / O会谈感兴趣:Building Android Applications that Use Web APIsWriting Efficient Drive Apps for Android

答案 1 :(得分:2)

我已回答了这个问题,以及所有相关的Android问题驱动器问题,在这里:

Android Open and Save files to/from Google Drive SDK

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

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;
    }
}

答案 2 :(得分:0)

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

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) {
    }
}