我正在编写一个 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错误请求
{
"error":"unauthorized_client"
}
我已经能够使用“云端硬盘”应用程序在 Android 平板电脑上访问“Google 云端硬盘”。所以
我的电子邮件帐户有效。可能是 AUTH_TOKEN_TYPE 不正确,但 Google 云端硬盘
SDK不清楚它一定是什么。我缺少什么?