如何从GoogleCredential获取访问令牌?

时间:2012-09-24 22:10:16

标签: authorization google-api oauth-2.0 credentials access-token

我正在尝试获取访问令牌以使用Google Play Android Developer API,而我使用the Google API Java Client documentation example得到了这一点:

HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();

GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(HTTP_TRANSPORT)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId("...gserviceaccount.com")
    .setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher")
    .setServiceAccountPrivateKeyFromP12File(keyFile)
    .build();

但是如何从此凭据获取访问令牌? credential.getAccessToken()返回null。我做错了什么,或者错过了一些步骤?

2 个答案:

答案 0 :(得分:49)

知道了。您必须在credential.getAccessToken()之前调用credential.refreshToken()。它并没有在文档中的任何地方说明这一点,但这就是它。

credential.refreshToken();
accessToken = credential.getAccessToken();

答案 1 :(得分:0)

如果使用ServiceAccountCredentials.fromStream()创建凭据对象,则可能也必须调用createScoped()方法。

    FileInputStream fileInputStream = new FileInputStream(KEY_FILE_PATH);
    GoogleCredentials credentials = ServiceAccountCredentials.fromStream(fileInputStream);
    credentials = credentials.createScoped(SCOPES);
    AccessToken accessToken = credentials.refreshAccessToken();

否则会出现错误

  

java.io.IOException:未为服务帐户配置范围。范围   应该通过调用createScoped或将范围传递给   构造函数。