我使用android AccountManager获取authToken,如下所示:
private void getGoogleAccountName(){
AccountManager.get(activity.getApplicationContext())
.getAuthTokenByFeatures("com.google", "oauth2:https://gdata.youtube.com", null, activity, null, null, this, null);
}
// I implement AccountManagerCallback<Bundle> in this class
@Override
public void run(AccountManagerFuture<Bundle> future) {
boolean hasAccount = checkGoogleAccount(future);
if (hasAccount) {
getYoutubeVideoByLib("");
}
}
private boolean checkGoogleAccount(AccountManagerFuture<Bundle> future){
try {
Bundle bundle = future.getResult();
accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
} catch (Exception e) {
return false;
}
return true;
}
然后我使用goh apis和authToken尝试获取用户的播放列表
private void getYoutubeVideoByLib(String pageToken){
YouTube youtube = new YouTube.Builder(
new NetHttpTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName(activity.getString(R.string.app_name)).build();
YouTube.Playlists.List query = null;
try{
query = youtube.playlists().list("snippet");
query.setOauthToken(authToken);
query.setKey("YOUTBE_API_KEY");
query.setMine(true);
if(!TextUtils.isEmpty(pageToken)) {
query.setPageToken(pageToken);
}
PlaylistListResponse response = query.execute();
...
} catch(IOException e) {
return;
}
}
但我发现一些谷歌帐户在query.execute()中遇到了GoogleJsonResponseException;
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开发者控制台中,我设置了API KEY但不设置OAuth 2.0客户端ID。 设置下面的代码并更改下面的代码后,它现在正常工作。
String[] SCOPES = {YouTubeScopes.YOUTUBE_READONLY};
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(SCOPES));
credential.setSelectedAccountName(accountName);
YouTube youtube = new YouTube.Builder(transport, jsonFactory, credential).setApplicationName(getString(R.string.app_name)).build();