使用java从Google Drive下载Google文档文件

使用java从Google Drive下载Google文档文件,java,google-api,google-drive-api,Java,Google Api,Google Drive Api,我正试图从谷歌硬盘下载一个文件。下载一个普通文件(pdf,jpg)没有任何问题。但我无法下载谷歌文件。我得到一个没有类型且大小为0的空文件。你知道这是什么原因吗 public InputStream download(String id) throws CloudServiceException { try { File file = service.files() .get(id) .execute();

我正试图从谷歌硬盘下载一个文件。下载一个普通文件(pdf,jpg)没有任何问题。但我无法下载谷歌文件。我得到一个没有类型且大小为0的空文件。你知道这是什么原因吗

public InputStream download(String id) throws CloudServiceException {
    try {
        File file = service.files()
                .get(id)
                .execute();
        String link = file.getExportLinks().get("application/pdf");
        HttpResponse resp = service.getRequestFactory()
                .buildGetRequest(
                        new GenericUrl(link))
                .execute();
        return resp.getContent();
    } catch (HttpResponseException e) {
        throw CloudServiceExceptionTransformer.transform(e, e.getStatusCode());
    } catch(IOException ex) {
        throw new InternalException(ex);
    }
}
您可以尝试以下方法:

URL url = new URL("http://www.gaertner-servatius.de/images/sinnfrage/kapitel-2/spacetime.gif");
InputStream inStream = url.openStream();
Files.copy(inStream, Paths.get("foobar.gif"), StandardCopyOption.REPLACE_EXISTING);
inStream.close();
试试这个:

 com.google.api.services.drive.Drive service;
 static InputStream download(String id)  {
   if (service != null && id != null) try {
     com.google.api.services.drive.model.File gFl =
        service.files().get(id).setFields("downloadUrl").execute();
     if (gFl != null){
       return service.getRequestFactory()
          .buildGetRequest(new GenericUrl(gFl.getDownloadUrl())).execute().getContent());
      }
    } catch (Exception e) { e.printStackTrace(); }
    return null;
  }

祝你好运

所以问题实际上在于建立一个响应。Google文件的大小为0,但无法识别Google媒体类型,这导致该文件损坏

编辑:这是我的工作版本。我删除了设置的大小,以便它下载那些0大小的文件

   ResponseEntity.BodyBuilder builder = ResponseEntity.status(HttpStatus.OK)
            .header(HttpHeaders.CONTENT_DISPOSITION, encoding)
            .contentType(MediaType.parseMediaType(resource.getMimeType()));
    return builder.body(new InputStreamResource(resource.getContent()));

您需要使用导出方法来下载谷歌文档或任何谷歌文件

String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
    .executeMediaAndDownloadTo(outputStream);

谢谢你的建议。这种方法的问题依然存在。我试过了,如果导出链接可以工作,当我手动使用它时,它也可以工作。谢谢你的建议。谷歌文档文件没有下载URL。我可以获得有效的exportLink,但我无法从代码中下载它。如果您有ID(它是一个类似“UW2ABLAHBLAHNY00UMS0B1MQ”的字符串),这有关系吗?我会获得ID(字符串)并在底部使用它,或者。