【问题标题】:Google Drive Rest API on AndroidAndroid 上的 Google Drive Rest API
【发布时间】:2015-11-28 07:39:48
【问题描述】:

我正在为一家公司开发一个应用,我需要将它与 Google 云端硬盘集成。我不能使用本机 API,因为公司有需要处理的不是由应用程序创建的文件,我需要完整的驱动器范围,所以我必须使用 REST API。

问题来了,因为我对 JSON 和 REST 只有非常基本的了解,所以这些教程对我来说还不够基础。

教程:https://developers.google.com/drive/web/integrate-create

据我了解,我需要在我的 Java 代码中创建 JSON,然后通过示例代码传递它?

JSON

{
  "action":"create",
  "folderId":"0ADK06pfg",
  "userId":"103354693083460731603"
}

JAVA

public class State {
  /**
   * Action intended by the state.
   */
  public String action;

  /**
   * IDs of files on which to take action.
   */
  public Collection<String> ids;

  /**
   * Parent ID related to the given action.
   */
  public String parentId;

  /**
   * Empty constructor required by Gson.
   */
  public State() {}

  /**
   * Create a new State given its JSON representation.
   *
   * @param json Serialized representation of a State.
   */

  public State(String json) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    State other = gson.fromJson(json, State.class);
    this.action = other.action;
    this.ids = other.ids;
    this.parentId = other.parentId;
  }
}

问题是我不知道如何创建 JSON,也不太了解如何在创建时使用 JSON 来执行创建文件和查询文件等操作。

如果有人可以让我在用户根文件夹中创建一个空文件,那么我可能可以从那里获取它,但我真的可以朝正确的方向轻推!

【问题讨论】:

    标签: android json rest google-drive-api google-drive-android-api


    【解决方案1】:

    假设您正在谈论一个 Android 应用程序,则无需创建 JSON。 Java REST Api 在 Android 上非常易于使用。如果官方文档和示例还不够,你可以看看这个demo。它需要稍微复杂一些(为了保持与 GDAA version 的兼容性),但是通过几个简单的步骤,您可以简化它。

    我当然不能复制这里的所有代码,但你可以抢夺REST class,提供一个 GooDrive 帐户到 setSelectedAccountName()(或省略该方法,让服务处理它)并简化 connect() / disconnect() 方法。 connect() 方法(为了与 GDAA 兼容)应该被替换为这样的 try/catch 构造:

    com.google.api.services.drive.Drive mGOOSvc;
    ...  
    try {
      mGOOSvc...execute();
    } catch (UserRecoverableAuthIOException uraIOEx) {  
      // standard authorization failure - user fixable
    } catch (GoogleAuthIOException gaIOEx) {  
      // usually PackageName / SHA1 mismatch in DevConsole
    } catch (IOException e) {   
      // '404 not found' in FILE scope, still, consider connected
      if (e instanceof GoogleJsonResponseException) {
        if (404 == ((GoogleJsonResponseException) e).getStatusCode())
          mConnected = true;
      }
    } catch (Exception e) {  
      // "the name must not be empty" indicates
      // UNREGISTERED / EMPTY account in 'setSelectedAccountName()' ???
    }
    

    您可以在 REST 类中找到“...execute()”方法的任何地方,以便捕获突然失去授权等...(随时可能发生)。否则,我已经运行这个 CRUD 实现一段时间了,从来没有遇到过问题。

    关于 REST Api 的一般说明。由于它是“依赖于网络状态的”,我建议将其与应用程序的 UI 完全断开连接,并在有活动网络(WIFI、蜂窝)流量时调用的某种类型的同步服务中运行它。见网络相关剧集here

    祝你好运

    【讨论】:

    • 嗨,肖恩。我下载了你的 REST 演示,效果很好。谢谢!但它不做的是列出另一个应用程序添加的文件,例如 Web 界面。我已经研究了几天,但我无法让应用程序列出除同一应用程序生成的文件之外的其他文件。您能告诉我如何在您的演示中实现这一点吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多