使用 Google Play 服务进行身份验证时一切正常:
String token = GoogleAuthUtil.getToken(mActivity, mEmail, "oauth2:" + DriveScopes.Drive);
使用令牌,我现在可以创建我的 Drive 实例并访问 Google Drive。但我意识到这仅支持 android 2.2 及更高版本。我需要支持android 2.1。
我尝试使用此代码来获取令牌:
AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.getAuthToken (
account,
"oauth2:" + DriveScopes.Drive,
options,
this,
new OnTokenAcquired(this),
null);
使用此代码时,我会得到一个令牌,但在使用它创建我的 Drive 实例时,我将无法访问 Google Drive。例如,当执行此代码时:
drive.files().list().setQ(trashed=false and title="'someTitle'").execute();
我会收到这个错误:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Invalid Credentials",
"reason" : "authError"
} ],
"message" : "Invalid Credentials"
}
这是创建我的 Drive 实例的方法:
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(CLIENT_ID);
driveRequest.setOauthToken(token);
driveRequest.setEnableGZipContent(true);
}
});
drive = b.build();