Refresh Token with Google API Java Client Library

2019-05-09 13:39发布

I'm using the Google API Java Client http://code.google.com/p/google-api-java-client/ and am able to get the access token successfully for Android.

    // Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, CalendarScopes.CALENDAR);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

As I'd like my web server to make offline API calls, I need a refresh token. I have been searching extensively and have not yet figured out how to do so.

Ideally, I'd prefer to use the Google API Java Client over the WebView to grab the refresh token (no need to enter a username or password).

Any help would be appreciated!

1条回答
ら.Afraid
2楼-- · 2019-05-09 14:18

You need to set the following when you initiate the authorization flow :

  • approval prompt = force
  • access type = false

With these params set, google will return a refresh token and the library will deal with refreshes. This works for me :

new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential(),
                Arrays.asList(SCOPES)).setCredentialStore(new OAuth2CredentialStore()).setAccessType("offline")
                .setApprovalPrompt("force").build();
查看更多
登录 后发表回答