【问题标题】:How to load file on google drive如何在谷歌驱动器上加载文件
【发布时间】:2012-06-28 22:23:51
【问题描述】:

我需要做的是在谷歌驱动器上加载文件。

我正在使用 GoogleAccountManager 通过 oauth2 进行授权并获得 AUTHTOKEN,现在不知道下一步该做什么。

要创建 Drive 对象,我需要 GoogleCredential 在哪里可以获得它们?

Drive service = new Drive(TRANSPORT, JSON_FACTORY, credential);

也许我应该做与Connect to the Online Service 教程类似的事情?

URL url = new URL("https://www.googleapis.com/tasks/v1/users/@me/lists?key=" + your_api_key);
URLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("client_id", your client id);
conn.addRequestProperty("client_secret", your client secret);
conn.setRequestProperty("Authorization", "OAuth " + token);

那么这个 url 来自哪里"https://www.googleapis.com/tasks/v1/users/@me/lists?key="

请给我建议或示例代码如何在谷歌驱动器上加载文件。谢谢。

【问题讨论】:

    标签: android google-drive-api


    【解决方案1】:

    这个答案现在已经过时了,因为 AccountManager 身份验证已被弃用,取而代之的是 Play Services。

    新答案

    private Drive service;
    private GoogleAccountCredential credential;
    
    credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
    credential.setSelectedAccountName(accountName);
    service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
    

    原答案

    我用过这个。 AuthToken 是您从 AccountManager 收到的令牌。 ApiKey 是您从Google Apis Console 获得的密钥。

    到目前为止似乎有效。文档很差。希望随着它的成熟,它会有所改善。它似乎是为那些已经知道他们在访问 G Api 的人所做的。一个完整的样本会节省很多时间。

    static Drive buildService(final String AuthToken, final String ApiKey) {
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
    
        Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
        b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
    
            @Override
            public void initialize(JsonHttpRequest request) throws IOException {
                DriveRequest driveRequest = (DriveRequest) request;
                driveRequest.setPrettyPrint(true);
                driveRequest.setKey(ApiKey);
                driveRequest.setOauthToken(AuthToken);
            }
        });
    
        return b.build();
    }
    

    【讨论】:

    • 您设置了哪种类型的应用程序来获取您的客户端 ID 以从 Google 的 API 控制台获取 ApiKey? (IE,你选择“Android”还是“Other”?)
    • setJsonHttpRequestInitializer 在我刚刚从 Google 下载的 Drive.Builder 版本中没有定义。知道发生了什么吗?
    • setGoogleClientRequestInitializer 看起来是一个可行的替代方案。
    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多