【问题标题】:Can we retrieve data back from Google Drive API in Android?我们可以从 Android 中的 Google Drive API 检索数据吗?
【发布时间】:2020-09-23 05:23:20
【问题描述】:

我能够使用 Google Drive 提供的 API 成功地将我的图像添加到 Google Drive。

我现在可以将其检索回我的应用程序吗? 如果是,有人可以帮忙吗?

【问题讨论】:

  • 查看此answer 可能对您有所帮助。

标签: android android-studio google-drive-android-api google-drive-realtime-api


【解决方案1】:

使用它从 Google Drive API 检索文件

https://www.googleapis.com/drive/v3/files/[FILEID]?key=[YOUR_API_KEY]'

如果您想要检索文件所需的全部代码,这里是:

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 java.io.IOException;
import java.io.InputStream;

// ...

public class MyClass {

  // ...

  /**
   * Print a file's metadata.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to print metadata for.
   */
  private static void printFile(Drive service, String fileId) {

    try {
      File file = service.files().get(fileId).execute();

      System.out.println("Title: " + file.getTitle());
      System.out.println("Description: " + file.getDescription());
      System.out.println("MIME type: " + file.getMimeType());
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
  }

  /**
   * 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();
        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;
    }
  }

  // ...
}

【讨论】:

  • 谢谢 Aayush,我在哪里编写/实现这个?
  • 将方法添加到您正在执行所有 API 工作的活动类中,并添加所有导入语句。确保您自定义代码的变量以与您的兼容。
  • 如果有效请接受我的回答,如果无效请告诉我。
  • 我是否必须为导入添加任何依赖项?
  • 不,不需要依赖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多