android - 下载文件错误【com.google.api.client.http.HttpResponseException : 401 Unauthorized]

标签 android google-drive-api

我在我的 Android 代码中使用以下代码,来自这里 https://developers.google.com/drive/v2/reference/files/get

一切正常,file.getDownloadUrl() 不为空,而且是一个非常长的 URL。

但是在获取 HttpResponse 响应时出现错误 401。

问题是什么?

我假设我已经获得授权,因为我可以在我的 GoogleDrive 中列出我的所有文件,获取 fileId 甚至 file.getDownloadUrl()。我的 OAuth2.0 范围是 DRIVE。

11-26 06:40:37.614: W/System.err(15750): com.google.api.client.http.HttpResponseException: 401 Unauthorized
11-26 06:40:37.614: W/System.err(15750):    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1062)

代码:

  /**
       * Download a file's content.
       *
       * @param service Drive API service instance.
       * @param file Drive File instance.
       * @return InputStream containing the file's content if successful,
       *         {@code null} otherwise.
       */
      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();  //--ERROR HERE--
            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;
        }
      }

日志:

11-26 06:50:04.638: I/fileId(16350): 0B2PmmdZsG0kJUTFNcWNaam9KLVE

11-26 06:50:07.896: I/file.getDownloadUrl()(16350): https://doc-0s-8g-docs.googleusercontent.com/docs/securesc/3l0k423jsgncap9ihfdfv9kb388vqac9/glhd2gbkatjpv4cb60383pc8b127o0l2/1353873600000/11834093636053924840/11834093636053924840/0B2PmmdZsG0kJUTFNcWNaam9KLVE?h=16653014193614665626&e=download&gd=true

最佳答案

确保参数service是你授权的Drive实例。如果不是这样,buildGetRequest 无法添加授权 header ,因为它不知道

关于android - 下载文件错误【com.google.api.client.http.HttpResponseException : 401 Unauthorized],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555916/

相关文章:

android - 使用 Android 和 Firebase 显示图片列表

android - 样式化 Android 自动完成

java - Android 程序因空指针异常而崩溃

android - Android中的全屏 Activity ?

java - Intent Action_dial 在 android 11 中不起作用

OCR 使用谷歌文档 API

FFMPEG 使用 Google Drive API 而不是共享 URL

javascript - Google 云端硬盘如何知道我安装了哪些应用程序?

node.js - 如何从Google Drive API导出方法正确地将PDF读入node js缓冲区?

google-apps-script - 如何转让 Google 电子表格的所有权并成为查看者