本文介绍了下载从谷歌驱动器文件中按URL在Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序来上传,展示和G盘下载文件。不幸的是当下载我越来越
  com.google.api.client.http.Htt presponseException:401未经授权

请帮我解决这个问题。

下面我分配

 凭证= GoogleAccountCredential.usingOAuth2(这一点,DriveScopes.DRIVE);

服务=新Drive.Builder(AndroidHttp.newCompatibleTransport(),新GsonFactory(),证书).build();
 

我的code是:

 包com.example.googledrive;

进口java.io.BufferedOutputStream;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口java.net.URLConnection中;
进口java.nio.channels.Channels;
进口java.nio.channels.ReadableByteChannel;
进口java.text.SimpleDateFormat的;
进口的java.util.ArrayList;
进口java.util.Date;
进口的java.util.List;
进口java.util.Locale中;

进口com.google.api.client.extensions.android.http.AndroidHttp;
进口com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
进口com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
进口com.google.api.client.http.FileContent;
进口com.google.api.client.http.GenericUrl;
进口com.google.api.client.http.Htt presponse;
进口com.google.api.client.json.gson.GsonFactory;
进口com.google.api.services.drive.Drive;
进口com.google.api.services.drive.Drive.Children;
进口com.google.api.services.drive.Drive.Files;
进口com.google.api.services.drive.Drive.Files.Get;
进口com.google.api.services.drive.DriveScopes;
进口com.google.api.services.drive.model.ChildList;
进口com.google.api.services.drive.model.ChildReference;
进口com.google.api.services.drive.model.File;
进口com.google.api.services.drive.model.FileList;

进口android.net.Uri;
进口android.os.Bundle;
进口android.os.Environment;
进口android.os.StrictMode;
进口android.provider.MediaStore;
进口android.accounts.AccountManager;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.ArrayAdapter;
进口android.widget.ListView;
进口android.widget.Toast;

公共类MainActivity延伸活动{

    静态最终诠释REQUEST_ACCOUNT_PICKER = 1;
    静态最终诠释REQUEST_AUTHORIZATION = 2;
    静态最终诠释CAPTURE_IMAGE = 3;

    私有静态乌里了fileURI;
    私人静态驱动的服务;
    私人ProgressDialog progressDialog;
    私人GoogleAccountCredential凭证;

    字符串FILEID;
    字符串文件名;
    字符串downloadUrl;
    ListView控件的ListView;
    活动活性;
    字符串sdCardPadth;
    名单<文件> allFileList;
    ArrayList的<字符串>文件类型;
    ArrayList的<字符串> mainTitleList;
    ArrayList的<字符串> fileIdList;
    ArrayList的<字符串> alternateUrlList;
    ArrayList的<整数GT; fileSizeList;
    FileTitlesAdapter myAdapter;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        ListView的=(的ListView)findViewById(R.id.uploadedFilesL​​ist);
        allFileList =新的ArrayList<文件>();
        mainTitleList =新的ArrayList<字符串>();
        alternateUrlList =新的ArrayList<字符串>();
        fileSizeList =新的ArrayList<整数GT;();
        的fileType =新的ArrayList<字符串>();
        fileIdList =新的ArrayList<字符串>();
        progressDialog =新ProgressDialog(getApplicationContext());
        progressDialog.setTitle(请等待......);
        progressDialog.setCancelable(假);
        活动=这一点;

        凭据= GoogleAccountCredential.usingOAuth2(这一点,DriveScopes.DRIVE);
        startActivityForResult(credential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
        listView.setOnItemClickListener(新AdapterView.OnItemClickListener(){
            公共无效onItemClick(适配器视图<>为arg0,视图中查看,最终诠释ARG2,长ARG3){
                //字符串str = itemArray.get(ARG2)的ToString()修剪()。
                的System.out.println(mainTitleList尺寸===+ mainTitleList.size());
                的System.out.println(ARG2 ===+ ARG2);
                文件名=(字符串)mainTitleList.get(ARG2);
                mainTitleList.clear();
                //fileSizeList.clear();
                最后弦乐fileTypeStr = fileType.get(ARG2);
                fileType.clear();
                如果(fileTypeStr.contains(应用/ vnd.google-apps.folder))
                {
                    线程t =新主题(新的Runnable(){
                        @覆盖
                        公共无效的run(){
                    布尔B =真实;
                    尝试 {
                        字符串dirUrl = alternateUrlList.get(ARG2);
                        alternateUrlList.clear();
                        的System.out.println(文件夹名称为:+文件名);
                        的System.out.println(文件夹类型是:+ fileTypeStr);
                        的System.out.println(文件夹的网址是:+ dirUrl);
                        字符串FILEID = fileIdList.get(ARG2);
                        的System.out.println(文件夹ID是:+ FILEID);
                        // retrieveAllFilesFromDir(服务,FILEID,B);
                        // retrieveAllFiles1(服务,B,FILEID);
                        //Files.List请求= service.children()得到(FILEID,空)。
                        Files.List请求= service.files()名单()setQ('+ FILEID +家长)。
                        retrieveAllFiles(服务请求,B);
                        // retrieveAllFiles(服务,B);
                    }赶上(例外五){
                        // TODO自动生成的catch块
                        的System.out.println(异常retrieveAllFiles dir是:+ E);
                        e.printStackTrace();
                    }
                        }
                        }); t.start();
                }
                其他
                {

                尝试 {
                    的System.out.println(fileSizeList尺寸====+ fileSizeList.size());
                    的System.out.println(ARG2 ====+ ARG2);
                    整数文件大小=(INT)fileSizeList.get(ARG2);
                    downloadUrl = alternateUrlList.get(ARG2);
                    byte []的大小=新的字节[文件大小]
                    INT byteRead = 0,byteWritten = 0;
                    sdCardPadth = Environment.getExternalStorageDirectory()getPath()。


                    的System.out.println(下载地址===+ downloadUrl);

                    新主题(新的Runnable(){

                        @覆盖
                        公共无效的run(){
                            // TODO自动生成方法存根
                            的InputStream inStream中= downloadFile(服务,downloadUrl);

                            java.io.File的INFILE =新的java.io.File(sdCardPadth +/+文件名+1);
                            的System.out.println(文件成功与存储);

                        }
                    })。开始();
                }赶上(例外五){
                    // TODO自动生成的catch块
                    的System.out.println(异常进去整数:+ E);
                    e.printStackTrace();
                }
                }
            }
        });
    }

    @覆盖
    保护无效onActivityResult(最终诠释请求code,
            最终诠释结果code,最终的意图数据){
        开关(要求code){
        案例REQUEST_ACCOUNT_PICKER:
            如果(结果code == RESULT_OK和放大器;&安培;!数据= NULL
                    &功放;&安培; data.getExtras()!= NULL){
                字符串帐户名=数据
                        .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                如果(帐户名!= NULL){
                    credential.setSelectedAccountName(帐户名);
                    服务= getDriveService(凭证);
                    最终布尔B = FALSE;
                    线程t =新主题(新的Runnable(){
                        @覆盖
                        公共无效的run(){
                            尝试
                            {
                                。Files.List请求= service.files()名单()setQ(隐藏=+ B);
                                    retrieveAllFiles(服务请求,B);
                            }赶上(例外五){
                                的System.out.println(例外是:+ E);
                                e.printStackTrace();
                            }

                        }
                    }); t.start();

                }
            }
            打破;
        案例REQUEST_AUTHORIZATION:
            如果(结果code == Activity.RESULT_OK){
                的System.out.println(REQUEST_AUTHORIZATION的情况是:
                        + REQUEST_AUTHORIZATION);
                saveFileToDrive();
            } 其他 {
                startActivityForResult(credential.newChooseAccountIntent(),
                        REQUEST_ACCOUNT_PICKER);
            }
            打破;
        案例CAPTURE_IMAGE:
            如果(结果code == Activity.RESULT_OK){
                的System.out.println(CAPTURE_IMAGE的情况是:+ CAPTURE_IMAGE);
                saveFileToDrive();
            }
        }
    }
    私人无效saveFileToDrive(){
        线程t =新主题(新的Runnable(){
            @覆盖
            公共无效的run(){
                尝试 {
                    //文件的二进制内容
                    的System.out.println(运行方式);
                    java.io.File的fileContent =新的java.io.File(fileUri.getPath());
                    FileContent mediaContent =新FileContent(图像/ JPEG,fileContent);
                    //文件的元数据。
                    文件主体=新的文件();
                    body.setTitle(fileContent.getName());
                    body.setMimeType(为image / jpeg);
                    文件fil​​e = NULL;
                    尝试 {

                        。文件= service.files()插入(身体,mediaContent).execute();
                    }赶上(例外五){

                        的System.out.println(异常在插入文件是+ E);
                        e.printStackTrace();
                    }
                    如果(文件!= NULL){
                        showToast(照片上载:+ file.getTitle());
                        的System.out.println(照片sucessfullly上传:+ FILEID);布尔B = FALSE;
。Files.List请求= service.files()名单()setQ(隐藏=+ B);
                        retrieveAllFiles(服务请求,B);
                    }
                }赶上(UserRecoverableAuthIOException E){
                    startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
    私人驱动器getDriveService(GoogleAccountCredential凭证){
        返回新Drive.Builder(AndroidHttp.newCompatibleTransport()
                新GsonFactory(),证书).build();
    }

    公共无效showToast(最后弦乐吐司){
        runOnUiThread(新的Runnable(){
            @覆盖
            公共无效的run(){
                Toast.makeText(getApplicationContext(),烤面包,Toast.LENGTH_SHORT).show();
            }
        });
    }

    私人列表<文件> retrieveAllFiles(驱动器服务,Files.List请求,布尔B)抛出IOException异常{
        名单<文件>结果=新的ArrayList<文件>();
        最后的ArrayList<字符串> titleList =新的ArrayList<字符串>();
        字符串fileUrl =;
        做 {
            尝试 {
                文件列表文件= request.execute();
                result.addAll(files.getItems());
                request.setPageToken(files.getNextPageToken());
                的for(int i = 0; I< result.size();我++){
                    文件临时文件= result.get(我);
                    串fileTypeStr = tempFile.getMimeType();
                    字符串文件名= tempFile.getTitle();
                    titleList.add(文件名);
                    FILEID = tempFile.getId();
                    fileIdList.add(FILEID);
                    fileUrl = tempFile.getAlternateLink();
                    的System.out.println(<><>< fileUrl是:+ fileUrl);
                    alternateUrlList.add(fileUrl);

                    fileType.add(fileTypeStr);
                    mainTitleList.add(文件名);

                    尝试 {
                        整数文件大小= tempFile.getFileSize()== NULL 100:?(INT)(长)tempFile.getFileSize();
                        fileSizeList.add(文件大小);
                        的System.out.println(<><><文件大小是:+文件大小);
                    }赶上(例外五){

                        fileSizeList.add(2000);
                        e.printStackTrace();
                    }


                }



                尝试 {
                    runOnUiThread(新的Runnable(){
                        公共无效的run(){

                            myAdapter =新FileTitlesAdapter(活动,
                                    的fileType,mainTitleList,alternateUrlList,
                                    fileSizeList);
                            listView.setAdapter(myAdapter);
                        }
                    });

                }赶上(例外五){


                    的System.out.println(异常设定的ListView是:+ E);
                    e.printStackTrace();
                }
            }赶上(IOException异常E){
                的System.out.println(在retrieveAllFiles出现错误:+ E);
                request.setPageToken(空);
            }
        }而(request.getPageToken()!= NULL
                &功放;&安培; request.getPageToken()长度()> 0);
        返回结果;
    }


     私有静态的InputStream downloadFile(驱动器服务,字符串URL){
         的System.out.println(downloadFile称为服务==+服务);
            如果(URL =空&安培;!&安培; url.length()大于0){
              尝试 {
                  的System.out.println(downloadFile被称为试);
                HTT presponse RESP = service.getRequestFactory()buildGetRequest(新GenericUrl(URL))执行()。
                的System.out.println(resp.getContent()====+ resp.getContent());
                返回resp.getContent();
              }赶上(例外五){
                的System.out.println(例外是:+ E);
                e.printStackTrace();
                返回null;
              }
            } 其他 {
                 的System.out.println(也不例外无输出);
              返回null;
            }
          }


}
 

解决方案

这是我使用从谷歌驱动器下载文件code

 新的AsyncTask<太虚,整数,布尔和GT;(){

        @覆盖
        保护布尔doInBackground(空... PARAMS){
        尝试 {
            文件fil​​e = service.files()获得(路径驱动器)执行()。
            java.io.File的TOFILE =新的java.io.File(要保存);
            toFile.createNewFile();
            HttpDownloadManager下载=新HttpDownloadManager(文件,TOFILE);
            downloader.setListener(新HttpDownloadManager.FileDownloadProgressListener(){

                公共无效downloadProgress(长读取动作,长tot​​alBytes){
                    Log.i(chauster,totalBytes);
                    Log.i(chauster,读取动作);
                }

                @覆盖
                公共无效downloadFinished(){
                    // TODO自动生成方法存根
                }

                @覆盖
                公共无效downloadFailedWithError(例外五){
                    // TODO自动生成方法存根
                }
            });
            返回downloader.download(服务);
        }赶上(IOException异常E){
            e.printStackTrace();
        }
            返回false;
        }
        保护无效onPostExecute(布尔结果){
        };
    }。执行();
 

HttpDownloadManager.java

 进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;

进口com.google.api.client.http.GenericUrl;
进口com.google.api.client.http.Htt presponse;
进口com.google.api.services.drive.Drive;
进口com.google.api.services.drive.model.File;
进口com.grandex.ShareInfomation.ShareData;
进口com.grandex.ShareInfomation.ShareData.ToolTapState;

公共类HttpDownloadManager {
    私人字符串donwloadUrl;
    私人字符串TOFILE;
    私人FileDownloadProgressListener监听;
    专用长totalBytes;

    公共无效使用setListener(FileDownloadProgressListener监听器){
        this.listener =侦听器;
    }

    公共HttpDownloadManager(文件的资源文件,java.io.File中destinationFile){
        超();
        this.donwloadUrl = sourceFile.getDownloadUrl();
        this.toFile = destinationFile.toString();
        this.totalBytes = sourceFile.getFileSize();
    }

    公共静态接口FileDownloadProgressListener {
        公共无效downloadProgress(长读取动作,长tot​​alBytes);

        公共无效downloadFinished();

        公共无效downloadFailedWithError(例外五);
    }

    公共布尔下载(驱动器服务){
        HTT presponse respEntity = NULL;
        尝试 {
            // URL网址=新的URL(urlString);
            respEntity = service.getRequestFactory()
                    。.buildGetRequest(新GenericUrl(donwloadUrl))执行();
            InputStream的时间= respEntity.getContent();
            如果(totalBytes == 0){
                totalBytes = respEntity.getContentLoggingLimit();
            }
            尝试 {
                FileOutputStream中F =新的FileOutputStream(TOFILE){

                    @覆盖
                    公共无效的write(byte []的缓冲区,诠释byteOffset,
                            INT BYTECOUNT)抛出IOException异常{
                        // TODO自动生成方法存根
                        super.write(缓冲,byteOffset,BYTECOUNT);
                        }
                    }
                };
                byte []的缓冲区=新的字节[1024];
                INT LEN1 = 0;
                长读取动作= 0;
                而((LEN1 = in.read(缓冲液))大于0){
                    f.write(缓冲液,0,LEN1);
                    如果(听众!= NULL){
                        读取动作+ = LEN1;
                        listener.downloadProgress(读取动作,totalBytes);
                    }
                }
                f.close();
            }赶上(例外五){
                如果(听众!= NULL){
                    listener.downloadFailedWithError(E);
                }
                返回false;
            }
            如果(听众!= NULL){
                listener.downloadFinished();
            }
            返回true;

        }赶上(IOException异常前){
            如果(听众!= NULL){
                listener.downloadFailedWithError(前);
                返回false;
            }
        } 最后 {
            如果(respEntity!= NULL){
                尝试 {
                    respEntity.disconnect();
                }赶上(IOException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }
            }
        }
        返回false;
    }
}
 

I am developing an app to uploading ,displaying and downloading files from G Drive. Unfortunately When downloading I am getting
com.google.api.client.http.HttpResponseException: 401 Unauthorized.

Please help me to solve this problem.

Here I am assigning

credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);

service=new Drive.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(),credential).build();

My Code Is:

package com.example.googledrive;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Children;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.Drive.Files.Get;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.ChildList;
import com.google.api.services.drive.model.ChildReference;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

    static final int REQUEST_ACCOUNT_PICKER = 1;
    static final int REQUEST_AUTHORIZATION = 2;
    static final int CAPTURE_IMAGE = 3;

    private static Uri fileUri;
    private static Drive service;
    private ProgressDialog progressDialog;
    private GoogleAccountCredential credential;

    String fileId;
    String fileName;
    String downloadUrl;
    ListView listView;
    Activity activity;
    String sdCardPadth;
    List<File> allFileList;
    ArrayList<String> fileType;
    ArrayList<String> mainTitleList;
    ArrayList<String> fileIdList;
    ArrayList<String> alternateUrlList;
    ArrayList<Integer> fileSizeList;
    FileTitlesAdapter myAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.uploadedFilesList);
        allFileList = new ArrayList<File>();
        mainTitleList = new ArrayList<String>();
        alternateUrlList = new ArrayList<String>();
        fileSizeList = new ArrayList<Integer>();
        fileType = new ArrayList<String>();
        fileIdList=new ArrayList<String>();
        progressDialog=new ProgressDialog(getApplicationContext());
        progressDialog.setTitle("Please Wait....");
        progressDialog.setCancelable(false);
        activity = this;

        credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
        startActivityForResult(credential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, final int arg2,long arg3) {
                // String str=itemArray.get(arg2).toString().trim();
                System.out.println("mainTitleList size==="+mainTitleList.size());
                System.out.println("arg2==="+arg2);
                fileName = (String)mainTitleList.get(arg2);
                mainTitleList.clear();
                //fileSizeList.clear();
                final String fileTypeStr=fileType.get(arg2);
                fileType.clear();
                if(fileTypeStr.contains("application/vnd.google-apps.folder"))
                {
                    Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                    boolean b=true;
                    try {
                        String dirUrl=alternateUrlList.get(arg2);
                        alternateUrlList.clear();
                        System.out.println("Folder Name Is:"+fileName);
                        System.out.println("Folder Type Is:"+fileTypeStr);
                        System.out.println("Folder URL Is:"+dirUrl);
                        String fileId=fileIdList.get(arg2);
                        System.out.println("Folder Id Is:"+fileId);
                        //retrieveAllFilesFromDir(service, fileId, b);
                        //retrieveAllFiles1(service, b, fileId);
                        //Files.List request = service.children().get(fileId, null);
                        Files.List request = service.files().list().setQ("'" + fileId + "' in parents ");
                        retrieveAllFiles(service,request,b);
                        //retrieveAllFiles(service, b);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        System.out.println("Exception In retrieveAllFiles Dir Is:"+e);
                        e.printStackTrace();
                    }
                        }
                        });t.start();
                }
                else
                {

                try {
                    System.out.println("fileSizeList size===="+fileSizeList.size());
                    System.out.println("arg2===="+arg2);
                    Integer fileSize = (int) fileSizeList.get(arg2);
                    downloadUrl = alternateUrlList.get(arg2);
                    byte[] size = new byte[fileSize];
                    int byteRead = 0, byteWritten = 0;
                    sdCardPadth = Environment.getExternalStorageDirectory().getPath();


                    System.out.println("Download Url==="+downloadUrl);

                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            InputStream inStream=downloadFile(service, downloadUrl);

                            java.io.File inFile=new java.io.File(sdCardPadth+"/"+fileName+"1");
                            System.out.println("File Succesfully Stored");

                        }
                    }).start();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    System.out.println("Exception In get Integer Is:" + e);
                    e.printStackTrace();
                }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(final int requestCode,
            final int resultCode, final Intent data) {
        switch (requestCode) {
        case REQUEST_ACCOUNT_PICKER:
            if (resultCode == RESULT_OK && data != null
                    && data.getExtras() != null) {
                String accountName = data
                        .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) {
                    credential.setSelectedAccountName(accountName);
                    service = getDriveService(credential);
                    final boolean b=false;
                    Thread t=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try
                            {
                                Files.List request = service.files().list().setQ("hidden="+b);
                                    retrieveAllFiles(service,request,b);
                            } catch (Exception e) {
                                System.out.println("Exception Is:"+e);
                                e.printStackTrace();
                            }

                        }
                    }) ;t.start();

                }
            }
            break;
        case REQUEST_AUTHORIZATION:
            if (resultCode == Activity.RESULT_OK) {
                System.out.println("REQUEST_AUTHORIZATION case Is:"
                        + REQUEST_AUTHORIZATION);
                saveFileToDrive();
            } else {
                startActivityForResult(credential.newChooseAccountIntent(),
                        REQUEST_ACCOUNT_PICKER);
            }
            break;
        case CAPTURE_IMAGE:
            if (resultCode == Activity.RESULT_OK) {
                System.out.println("CAPTURE_IMAGE case Is:" + CAPTURE_IMAGE);
                saveFileToDrive();
            }
        }
    }
    private void saveFileToDrive() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // File's binary content
                    System.out.println("run method");
                    java.io.File fileContent = new java.io.File(fileUri.getPath());
                    FileContent mediaContent = new FileContent("image/jpeg",fileContent);
                    // File's metadata.
                    File body = new File();
                    body.setTitle(fileContent.getName());
                    body.setMimeType("image/jpeg");
                    File file=null;
                    try {

                        file = service.files().insert(body, mediaContent).execute();
                    } catch (Exception e) {

                        System.out.println("Exception In Insert File Is"+e);
                        e.printStackTrace();
                    }
                    if (file != null) {
                        showToast("Photo uploaded: " + file.getTitle());
                        System.out.println("photo sucessfullly uploaded:"+ fileId);boolean b=false;
Files.List request = service.files().list().setQ("hidden="+b);
                        retrieveAllFiles(service,request,b);
                    }
                } catch (UserRecoverableAuthIOException e) {
                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
    private Drive getDriveService(GoogleAccountCredential credential) {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
                new GsonFactory(), credential).build();
    }

    public void showToast(final String toast) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), toast,Toast.LENGTH_SHORT).show();
            }
        });
    }

    private List<File> retrieveAllFiles(Drive service,Files.List request,boolean b) throws IOException {
        List<File> result = new ArrayList<File>();
        final ArrayList<String> titleList = new ArrayList<String>();
        String fileUrl = "";
        do {
            try {
                FileList files = request.execute();
                result.addAll(files.getItems());
                request.setPageToken(files.getNextPageToken());
                for (int i = 0; i < result.size(); i++) {
                    File tempFile = result.get(i);
                    String fileTypeStr = tempFile.getMimeType();
                    String fileName = tempFile.getTitle();
                    titleList.add(fileName);
                    fileId = tempFile.getId();
                    fileIdList.add(fileId);
                    fileUrl = tempFile.getAlternateLink();
                    System.out.println("<><>< fileUrl Is:" + fileUrl);
                    alternateUrlList.add(fileUrl);

                    fileType.add(fileTypeStr);
                    mainTitleList.add(fileName);

                    try {
                        Integer fileSize =tempFile.getFileSize()==null?100:(int) (long) tempFile.getFileSize();
                        fileSizeList.add(fileSize);
                        System.out.println("<><>< fileSize Is:" + fileSize);
                    } catch (Exception e) {

                        fileSizeList.add(2000);
                        e.printStackTrace();
                    }


                }



                try {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            myAdapter = new FileTitlesAdapter(activity,
                                    fileType, mainTitleList, alternateUrlList,
                                    fileSizeList);
                            listView.setAdapter(myAdapter);
                        }
                    });

                } catch (Exception e) {


                    System.out.println("Exception Setting ListView Is:" + e);
                    e.printStackTrace();
                }
            } catch (IOException e) {
                System.out.println("An error occurred in retrieveAllFiles:"+ e);
                request.setPageToken(null);
            }
        } while (request.getPageToken() != null
                && request.getPageToken().length() > 0);
        return result;
    }


     private static InputStream downloadFile(Drive service, String url) {
         System.out.println("downloadFile is called service=="+service);
            if (url != null && url.length() > 0) {
              try {
                  System.out.println("downloadFile is called try");
                HttpResponse resp =service.getRequestFactory().buildGetRequest(new GenericUrl(url)).execute();
                System.out.println("resp.getContent()===="+resp.getContent());
                return resp.getContent();
              } catch (Exception e) {
                System.out.println("Exception Is:"+e);
                e.printStackTrace();
                return null;
              }
            } else {
                 System.out.println("No Exception No Output");
              return null;
            }
          }


}
解决方案

This is code that I use to download File from google Drive

   new AsyncTask<Void, Integer, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... params) {
        try {
            File file = service.files().get("path in drive").execute();
            java.io.File toFile = new java.io.File("where you want to store");
            toFile.createNewFile();
            HttpDownloadManager downloader = new HttpDownloadManager(file, toFile);
            downloader.setListener(new HttpDownloadManager.FileDownloadProgressListener() {

                public void downloadProgress(long bytesRead, long totalBytes) {
                    Log.i("chauster",totalBytes);
                    Log.i("chauster",bytesRead);
                }

                @Override
                public void downloadFinished() {
                    // TODO Auto-generated method stub
                }

                @Override
                public void downloadFailedWithError(Exception e) {
                    // TODO Auto-generated method stub
                }
            });
            return downloader.download(service);
        } catch (IOException e) {
            e.printStackTrace();
        }
            return false;
        }
        protected void onPostExecute(Boolean result) {
        };
    }.execute();

HttpDownloadManager.java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.grandex.ShareInfomation.ShareData;
import com.grandex.ShareInfomation.ShareData.ToolTapState;

public class HttpDownloadManager {
    private String donwloadUrl;
    private String toFile;
    private FileDownloadProgressListener listener;
    private long totalBytes;

    public void setListener(FileDownloadProgressListener listener) {
        this.listener = listener;
    }

    public HttpDownloadManager(File sourceFile, java.io.File destinationFile) {
        super();
        this.donwloadUrl = sourceFile.getDownloadUrl();
        this.toFile = destinationFile.toString();
        this.totalBytes = sourceFile.getFileSize();
    }

    public static interface FileDownloadProgressListener {
        public void downloadProgress(long bytesRead, long totalBytes);

        public void downloadFinished();

        public void downloadFailedWithError(Exception e);
    }

    public boolean download(Drive service) {
        HttpResponse respEntity = null;
        try {
            // URL url = new URL(urlString);
            respEntity = service.getRequestFactory()
                    .buildGetRequest(new GenericUrl(donwloadUrl)).execute();
            InputStream in = respEntity.getContent();
            if(totalBytes == 0) {
                totalBytes = respEntity.getContentLoggingLimit();
            }
            try {
                FileOutputStream f = new FileOutputStream(toFile) {

                    @Override
                    public void write(byte[] buffer, int byteOffset,
                            int byteCount) throws IOException {
                        // TODO Auto-generated method stub
                        super.write(buffer, byteOffset, byteCount);
                        }
                    }
                };
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long bytesRead = 0;
                while ((len1 = in.read(buffer)) > 0) {
                    f.write(buffer, 0, len1);
                    if (listener != null) {
                        bytesRead += len1;
                        listener.downloadProgress(bytesRead, totalBytes);
                    }
                }
                f.close();
            } catch (Exception e) {
                if (listener != null) {
                    listener.downloadFailedWithError(e);
                }
                return false;
            }
            if (listener != null) {
                listener.downloadFinished();
            }
            return true;

        } catch (IOException ex) {
            if (listener != null) {
                listener.downloadFailedWithError(ex);
                return false;
            }
        } finally {
            if(respEntity != null) {
                try {
                    respEntity.disconnect();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}

这篇关于下载从谷歌驱动器文件中按URL在Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 01:11