如何使用驱动api java从google drive下载文件?

如何使用驱动api java从google drive下载文件?,java,google-drive-api,Java,Google Drive Api,我试过谷歌硬盘的一些功能,但我无法从硬盘下载文件 这是我使用的代码 private static InputStream downloadFile(Drive service, File file) { if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { try { HttpResponse resp = servic

我试过谷歌硬盘的一些功能,但我无法从硬盘下载文件

这是我使用的代码

private static InputStream downloadFile(Drive service, File file) {
    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
      try {
        HttpResponse resp =
            service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
                .execute();
        return resp.getContent();
      } catch (IOException e) {
        // An error occurred.
        e.printStackTrace();
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }
  }
当我运行脚本时,它显示
file.getDownloadUrl()
为空

我错过了什么

现在,在我调用下载函数之前,它在添加以下行之后执行

File file1 = service.files().get(fileid).execute();
downloadFile(service,file1);

现在的问题是如何借助我从脚本中获得的“response”下载文件……

Google Docs原生格式的文档不会有
downloadUrl
字段,相反,您可以使用
exportLinks
集合导出它们:


这是我从谷歌硬盘下载的文件,希望它能帮助你

/**应用程序名称*/
私有静态最终字符串应用程序\u NAME=“驱动API Java快速启动”;
/**用于存储此应用程序的用户凭据的目录*/
private static final java.io.File DATA_STORE_DIR=new java.io.File(
System.getProperty(“user.home”),
“.credentials/n/drive java quickstart”);
/**{@link FileDataStoreFactory}的全局实例*/
私有静态文件数据存储工厂数据存储工厂;
/**JSON工厂的全局实例*/
私有静态最终JsonFactory JSON_FACTORY=JacksonFactory
.getDefaultInstance();
/**HTTP传输的全局实例*/
专用静态HttpTransport HTTP_传输;
/**
*此快速启动所需作用域的全局实例。
* 
*如果修改这些作用域,请删除以前保存的凭据
*~/.credentials/驱动器java快速启动
*/
私有静态最终java.util.Collection SCOPES=DriveScopes
.全部();
静止的{
试一试{
HTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
DATA\u STORE\u FACTORY=新文件datastorefactory(DATA\u STORE\u DIR);
}捕获(可丢弃的t){
t、 printStackTrace();
系统出口(1);
}
}
/**
*创建授权凭据对象。
* 
*@返回授权凭证对象。
*@抛出异常
*/
公共静态凭据授权()引发IOException{
//加载客户端机密。
InputStream in=Quickstart.class
.getResourceAsStream(“/client_secret.json”);
GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(
JSON_工厂,新InputStreamReader(in));
//生成流并触发用户授权请求。
GoogleAuthorizationCodeFlow=新建GoogleAuthorizationCodeFlow.Builder(
HTTP_传输、JSON_工厂、客户端机密、作用域)
.setDataStoreFactory(数据存储工厂)
.setAccessType(“脱机”).build();
Credential Credential=新授权代码InstalledApp(流程,
新建LocalServerReceiver())。授权(“用户”);
System.out.println(“凭证保存到”
+数据存储目录getAbsolutePath());
返回凭证;
}
/**
*生成并返回授权驱动器客户端服务。
* 
*@返回授权驱动器客户端服务
*@抛出异常
*/
公共静态驱动器getDriveService()引发IOException{
凭证=授权();
返回新的Drive.Builder(HTTP_传输、JSON_工厂、凭证)
.setApplicationName(应用程序名称).build();
}
公共静态void main(字符串[]args)引发IOException{
//构建新的授权API客户端服务。
驱动器服务=getDriveService();
//打印最多10个文件的名称和ID。
FileList结果=service.files().list().execute();
List files=result.getFiles();
如果(files==null | | files.size()==0){
System.out.println(“未找到文件”);
}否则{
用于(文件:文件){
字符串fname=file.getName();
字符串ex=fname.substring(fname.lastIndexOf(“.”+1);
试一试{
Files f=service.Files();
HttpResponse HttpResponse=null;
如果(例如,等效信号情况(“xlsx”)){
httpResponse=f
.export(文件.getId(),
“application/vnd.openxmlformats of icedocument.spreadsheetml.sheet”)
.executeMedia();
}否则,如果(例如,等效信号情况(“docx”)){
httpResponse=f
.export(文件.getId(),
“application/vnd.openxmlformats of icedocument.wordprocessingml.document”)
.executeMedia();
}否则,如果(例如同等信号(“pptx”)){
httpResponse=f
.export(文件.getId(),
“application/vnd.openxmlformats of cedocument.presentationml.presentation”)
.executeMedia();
}else if(例如equalsIgnoreCase(“pdf”)
||ex.equalsIgnoreCase(“jpg”)
||例如,等效信号(png){
Get=f.Get(file.getId());
httpResponse=get.executeMedia();
}
if(null!=httpResponse){
InputStream instream=httpResponse.getContent();
FileOutputStream输出=新FileOutputStream(
getName());
试一试{
int l;
字节[]tmp=新字节[2048];
而((l=流内读取(tmp))!=-1){
输出写入(tmp,0,l);
}
}最后{
output.close();
流内关闭();
}
}
}捕获(例外e){
e、 printStackTrace();
}
}
}

我不熟悉这个……这里的服务是什么?我们如何称呼这个方法?我理解
/** Application name. */
private static final String APPLICATION_NAME = "Drive API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
        System.getProperty("user.home"),
        ".credentials/n/drive-java-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory
        .getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/**
 * Global instance of the scopes required by this quickstart.
 * 
 * If modifying these scopes, delete your previously saved credentials at
 * ~/.credentials/drive-java-quickstart
 */
private static final java.util.Collection<String> SCOPES = DriveScopes
        .all();

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 * 
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = Quickstart.class
            .getResourceAsStream("/client_secret.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline").build();
    Credential credential = new AuthorizationCodeInstalledApp(flow,
            new LocalServerReceiver()).authorize("user");
    System.out.println("Credentials saved to "
            + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

/**
 * Build and return an authorized Drive client service.
 * 
 * @return an authorized Drive client service
 * @throws IOException
 */
public static Drive getDriveService() throws IOException {
    Credential credential = authorize();
    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME).build();
}

public static void main(String[] args) throws IOException {
    // Build a new authorized API client service.
    Drive service = getDriveService();
    // Print the names and IDs for up to 10 files.
    FileList result = service.files().list().execute();
    List<File> files = result.getFiles();
    if (files == null || files.size() == 0) {
        System.out.println("No files found.");
    } else {

        for (File file : files) {

            String fname = file.getName();
            String ex = fname.substring(fname.lastIndexOf(".") + 1);

            try {
                Files f = service.files();
                HttpResponse httpResponse = null;
                if (ex.equalsIgnoreCase("xlsx")) {
                    httpResponse = f
                            .export(file.getId(),
                                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                            .executeMedia();

                } else if (ex.equalsIgnoreCase("docx")) {
                    httpResponse = f
                            .export(file.getId(),
                                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                            .executeMedia();
                } else if (ex.equalsIgnoreCase("pptx")) {
                    httpResponse = f
                            .export(file.getId(),
                                    "application/vnd.openxmlformats-officedocument.presentationml.presentation")
                            .executeMedia();

                } else if (ex.equalsIgnoreCase("pdf")
                        || ex.equalsIgnoreCase("jpg")
                        || ex.equalsIgnoreCase("png")) {

                    Get get = f.get(file.getId());
                    httpResponse = get.executeMedia();

                }
                if (null != httpResponse) {
                    InputStream instream = httpResponse.getContent();
                    FileOutputStream output = new FileOutputStream(
                            file.getName());
                    try {
                        int l;
                        byte[] tmp = new byte[2048];
                        while ((l = instream.read(tmp)) != -1) {
                            output.write(tmp, 0, l);
                        }
                    } finally {
                        output.close();
                        instream.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }