gpt4 book ai didi

java - 使用 AccountManager 通过 Google API 进行身份验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:38:16 25 4
gpt4 key购买 nike

这几天我一直在努力解决这个问题。我正在尝试通过 Android 的 AccountManager 使用身份验证来调用 Google 日历。我使用通常的方法检索身份验证 token :

AccountManager manager = AccountManager.get(this);
String authToken = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);

然后,使用该标记,我创建了一个 Calendar 实例,如下所示:

HttpTransport transport = AndroidHttp.newCompatibleTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
Calendar calendar = Calendar.builder(transport, jsonFactory).setApplicationName("MyApp/1.0").setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
@Override
public void initialize(JsonHttpRequest request) {
CalendarRequest calendarRequest = (CalendarRequest) request;
calendarRequest.setKey(API_KEY);
}
}).setHttpRequestInitializer(accessProtectedResource).build();

但是,当我使用它进行 API 调用时,我收到如下所示的 401 Unauthorized 错误。请注意,我已经包含了使过期的身份验证 token 无效的代码,所以我认为这不是这里的问题。

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"
}

关于我可能做错了什么的想法?

最佳答案

是的,这是可能的。一旦您掌握了 Google 帐户(如您所述),您只需从 AccountManager 请求 GData 服务的授权 token 。

如果 Android 设备已经有一个授权 token (针对您尝试访问的特定 GData 服务),它将返回给您。如果没有,AccountManager 将请求一个并将其返回给您。无论哪种方式,您都无需担心,因为 AccountManager 会处理它。

在以下示例中,我使用的是 Google Spreadsheets API:

ArrayList<Account> googleAccounts = new ArrayList<Account>();

// Get all accounts
Account[] accounts = accountManager.getAccounts();
for(Account account : accounts) {
// Filter out the Google accounts
if(account.type.compareToIgnoreCase("com.google")) {
googleAccounts.add(account);
}
}
AccountManager accountManager = AccountManager.get(activity);

// Just for the example, I am using the first google account returned.
Account account = googleAccounts.get(0);

// "wise" = Google Spreadheets
AccountManagerFuture<Bundle> amf = accountManager.getAuthToken(account, "wise", null, activity, null, null);

try {
Bundle authTokenBundle = amf.getResult();
String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);

// do something with the token
InputStream response = sgc.getFeedAsStream(feedUrl, authToken, null, "2.1");

}

请看sample code在谷歌数据 API 中。身份验证后要做的重要事情是调用 GoogleHeaders.setGoogleLogin(String)。

希望对您有所帮助。

关于java - 使用 AccountManager 通过 Google API 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9527751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com