3

我正在编写一个 Android(版本 ICS)应用程序。它将数据上传到 Google Drive。该应用程序使用 oauth2 获取访问令牌。

第一步:获取授权令牌。

    String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/drive";
    // Step 1
    accountManager.getAuthToken(
        account,                                // Account retrieved using getAccountsByType("com.google")
        AUTH_TOKEN_TYPE,                        // Auth Token Type
        options,                                // Authenticator-specific options
        this,                                   // Your activity
        new OnTokenAcquired(),                  // Callback called when a token is successfully acquired
        new Handler(new OnAuthTokenError()));   // Callback called if an error occurs
}
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        // Get the result of the operation from the AccountManagerFuture.
        Bundle bundle;
        try {
            bundle = result.getResult();

            authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);

            Log.d(TAG,"authToken:" + authToken);

            exchangeToken access = (exchangeToken) new exchangeToken().execute();

        } catch (OperationCanceledException e) {
            e.printStackTrace();
        } catch (AuthenticatorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

成功。获取授权令牌。

第 2 步:交换访问令牌的授权令牌。

    private class exchangeToken extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... params) {
        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new GsonFactory();
        String CLIENT_ID = "999999999999.apps.googleusercontent.com";
        String CLIENT_SECRET = "axXXXXXXXXXXXXXXX7";

        try { // Step 2: Exchange for an access and refresh token
            GoogleTokenResponse authResponse = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, authToken, CALLBACK_URL).execute();
            accessToken = authResponse.getAccessToken();
            Log.d("Get Access","Token:" + accessToken);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}  

失败。LogCat 显示以下内容:com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request

{

 "error":"unauthorized_client"

}

我已经能够使用“Drive”应用程序在我的 Android 平板电脑上访问“Google Drive”。所以我的电子邮件帐户是有效的。可能是 AUTH_TOKEN_TYPE 不正确,但 Google Drive SDK 并不清楚它必须是什么。我错过了什么?

4

2 回答 2

1

您不需要执行第二步交换令牌。Android 直接授予您访问令牌,它不会授予您必须交换令牌的身份验证代码。

Android 文档上的这个页面很好地解释了一切。

于 2012-05-25T20:49:11.507 回答
0

您知道要使用 Drive API,您的用户必须在 Chrome(!) Webstore 上安装您的应用程序吗?通常,文档列表 API 是 Android 的更好选择。

于 2012-05-26T08:14:12.813 回答