How to get access token from GoogleCredential?

佐手、 提交于 2019-11-27 05:37:10

问题


I am trying to get an access token to use the Google Play Android Developer API, and I got this far using 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();

But how do I get the access token from this credential? credential.getAccessToken() returns null. Am I doing something wrong, or missing some steps?


回答1:


Got it. You have to call credential.refreshToken() before credential.getAccessToken(). It doesn't say this anywhere in the documentation but that's what does it.

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



回答2:


If you use ServiceAccountCredentials.fromStream() to create your credential object, you may have to call the createScoped() method too.

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

Otherwise you get the error

java.io.IOException: Scopes not configured for service account. Scoped should be specified by calling createScoped or passing scopes to constructor.



来源:https://stackoverflow.com/questions/12573635/how-to-get-access-token-from-googlecredential

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!