API从谷歌驱动器下载文件

API从谷歌驱动器下载文件

本文介绍了如何使用Drive.API从谷歌驱动器下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为了得到与用户同步用户的应用程序数据驱动账号正在使用谷歌Drive.Api。

用户数据库为SQLite数据库格式。我已经成功上传的文件以二进制的驱动器,但未能从应用程序内下载该文件。

我如何得到文件网址:

 最后GoogleAccountCredential凭证= GoogleAccountCredential.usingOAuth2(这一点,Arrays.asList(DriveScopes.DRIVE_FILE));
    credential.setSelectedAccountName(帐户名);
    服务=新com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(),新GsonFactory(),证书).build();    查询查询=新Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLEBackupFile))
            。建立();
    最后DRIVEFOLDER文件夹= Drive.DriveApi.getRootFolder(mGoogleApiClient);
    folder.queryChildren(mGoogleApiClient,查询).setResultCallback(新ResultCallback< D​​riveApi.MetadataBufferResult>(){
        @覆盖
        公共无效onResult(DriveApi.MetadataBufferResult me​​tadataBufferResult){
            最终MetadataBuffer metadataBuffer = metadataBufferResult.getMetadataBuffer();
            诠释ICOUNT = metadataBuffer.getCount();            如果(ICOUNT == 1){
                Log.i(变量,找到文件);
                最终驱动器Id myFileId = metadataBuffer.get(0).getDriveId();
                最后DriveFile文件= Drive.DriveApi.getFile(mGoogleApiClient,myFileId);                新主题(新的Runnable接口(){
                    @覆盖
                    公共无效的run(){
                        DriveResource.MetadataResult mdRslt = file.getMetadata(mGoogleApiClient).await();
                        如果(mdRslt =空&放大器;!&放大器; mdRslt.getStatus()isSuccess()){
                            字符串link = mdRslt.getMetadata()getWebContentLink()。
                            Log.d(TAG,链接到文件:+链接);
                             DownloadBackup(链接);
                        }
                    }
                })。开始();            }
            metadataBuffer.release();
        }
    });

尝试通过下载的文件:

 公共无效DownloadBackup(字符串URL){
        InputStream的mInput = NULL;
        FileOutputStream中mOutput = NULL;
        如果(URL =空&放大器;!&放大器; url.length()大于0){
        尝试{
                GoogleAccountCredential CRD = GoogleAccountCredential.usingOAuth2(这一点,Arrays.asList(DriveScopes.DRIVE_FILE));
                crd.setSelectedAccountName(帐户名);
                com.google.api.services.drive.Drive SRV =新c​​om.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(),新GsonFactory(),CRD).build();
                。mInput = srv.getRequestFactory()buildGetRequest(新GenericUrl(URL))的execute()的getContent()。
                字符串outFileName = getApplicationContext()getDatabasePath(DatabaseHandler.DATABASE_NAME).getPath()。
                mOutput =新的FileOutputStream(outFileName);
                字节[] = mBuffer新的字节[1024];
                INT mLength;
                而((mLength = mInput.read(mBuffer))大于0){
                    mOutput.write(mBuffer,0,mLength);
                }
                mOutput.flush();
                Log.d(TAG,成功下载内容);
            }赶上(IOException异常五){
                e.printStackTrace();
            } {最后
                尝试{
                    //关闭流
                    如果(mOutput!= NULL){
                        mOutput.close();
                    }
                    如果(mInput!= NULL){
                        mInput.close();
                    }
                }赶上(IOException异常五){
                    Log.e(变量,无法关闭数据库);
                }
            }
        }其他{
            //该文件没有存储在云端硬盘的任何内容。
            //返回null;
            Log.e(变量,关于驱动有内容);
        }
    }

错误日志:

  W / System.err的:com.google.api.client.http.Htt presponseException:401未授权
W / System.err的:其中,HTML>
W / System.err的:其中; HEAD>
W / System.err的:其中; TITLE>未经授权< / TITLE>
W / System.err的:其中; / HEAD>
W / System.err的:其中; BODY BGCOLOR =#FFFFFFTEXT =#000000>
W / System.err的:其中; H1>未授权&下; / H1>
W / System.err的:其中; H2>错误401 LT; / H2>
W / System.err的:其中; / BODY>
W / System.err的:其中; / HTML>
W / System.err的:11月6日至12日:01:05.447 26208:26236 W / System.err的]
        在com.google.api.client.http.Htt prequest.execute(HTT prequest.java:1061)
W / System.err的:在com.example.app.activities.Main.DownloadBackup(Main.java:487)
W / System.err的:在com.example.app.activities.Main $ 15 $ 1.run(Main.java:332)
W / System.err的:在java.lang.Thread.run(Thread.java:841)


解决方案

下面是我如何做到这一点成功。相反,节能getWebContentLink'的结果,我保存的文件/文件夹ID(它是一个字符串)。并通过此ID像这样的方法:

  / ********* ************************************
   *获取文件内容
   * @参数渣油文件驱动器Id
   * @返回文件的内容/空的失败
   * /
  静态InputStream读(字符串渣油){
    如果(mGOOSvc = NULL&放大器;!&安培; mConnected和放大器;&安培;!渣油= NULL){尝试
      文件GFL = mGOOSvc.files()获得(渣油).setFields(downloadUrl),执行()。
      如果(GFL!= NULL){
        串strUrl = gFl.getDownloadUrl();
        返回mGOOSvc.getRequestFactory()
        .buildGetRequest(新GenericUrl(strUrl))的execute()的getContent()。
      }
    }赶上(例外五){/ *错误处理* /}
    返回null;
  }

检索downloadURL,并获得该内容。这个完整的上下文方法可以看出。

好运

I am using Google Drive.Api in order to get user's app data synced with users drive account.

The user database is in sqlite database format. I have successfully uploaded the file in binary to the drive but failing to download the file from within the app.

How I get the file URl :

  final GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
    credential.setSelectedAccountName(accountName);
    service = new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();

    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, "BackupFile"))
            .build();


    final DriveFolder folder = Drive.DriveApi.getRootFolder(mGoogleApiClient);
    folder.queryChildren(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
            final MetadataBuffer metadataBuffer = metadataBufferResult.getMetadataBuffer();
            int iCount = metadataBuffer.getCount();

            if (iCount == 1) {
                Log.i("Tag", "file was found");
                final DriveId myFileId = metadataBuffer.get(0).getDriveId();
                final DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, myFileId);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DriveResource.MetadataResult mdRslt = file.getMetadata(mGoogleApiClient).await();
                        if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
                            String link = mdRslt.getMetadata().getWebContentLink();
                            Log.d("TAG", "Link to File:" + link);
                             DownloadBackup(link);
                        }
                    }
                }).start();

            }
            metadataBuffer.release();
        }
    });

Trying to download the File via:

public void DownloadBackup(String url){
        InputStream mInput=null;
        FileOutputStream mOutput=null;
        if(url != null && url.length() > 0 ){
        try {
                GoogleAccountCredential crd = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
                crd.setSelectedAccountName(accountName);
                com.google.api.services.drive.Drive srv = new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), crd).build();
                mInput = srv.getRequestFactory().buildGetRequest(new GenericUrl(url)).execute().getContent();
                String outFileName = getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME).getPath();
                mOutput = new FileOutputStream(outFileName);
                byte[] mBuffer = new byte[1024];
                int mLength;
                while ((mLength = mInput.read(mBuffer)) > 0) {
                    mOutput.write(mBuffer, 0, mLength);
                }
                mOutput.flush();
                Log.d("TAG", "Successfully Downloaded contents");
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    //Close the streams
                    if(mOutput != null){
                        mOutput.close();
                    }
                    if(mInput != null){
                        mInput.close();
                    }
                } catch (IOException e) {
                    Log.e("Tag", "failed to close databases");
                }
            }
        } else {
            // The file doesn't have any content stored on Drive.
            // return null;
            Log.e("Tag", "No content on Drive");
        }
    }

Error Log:

W/System.err﹕ com.google.api.client.http.HttpResponseException: 401 Unauthorized
W/System.err﹕ <HTML>
W/System.err﹕ <HEAD>
W/System.err﹕ <TITLE>Unauthorized</TITLE>
W/System.err﹕ </HEAD>
W/System.err﹕ <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
W/System.err﹕ <H1>Unauthorized</H1>
W/System.err﹕ <H2>Error 401</H2>
W/System.err﹕ </BODY>
W/System.err﹕ </HTML>
W/System.err﹕ [ 06-12 11:01:05.447 26208:26236 W/System.err ]
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1061)
W/System.err﹕ at com.example.app.activities.Main.DownloadBackup(Main.java:487)
W/System.err﹕ at com.example.app.activities.Main$15$1.run(Main.java:332)
W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
解决方案

Here is how I do it successfully. Instead of saving the result of 'getWebContentLink', I save a file/folder ID (it is a string). And pass this ID to a method like this one:

 /*************************************************************************
   * get file contents
   * @param resId  file driveId
   * @return       file's content  / null on fail
   */
  static InputStream read(String resId) {
    if (mGOOSvc != null && mConnected && resId != null) try {
      File gFl = mGOOSvc.files().get(resId).setFields("downloadUrl").execute();
      if (gFl != null){
        String strUrl = gFl.getDownloadUrl();
        return mGOOSvc.getRequestFactory()
        .buildGetRequest(new GenericUrl(strUrl)).execute().getContent();
      }
    } catch (Exception e) { /* error handling */ }
    return null;
  }

retrieving a "downloadURL" and get the content. The full context of this method can be seen here.

Good Luck

这篇关于如何使用Drive.API从谷歌驱动器下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 13:55