Handling expired access token in Android without u

2019-01-29 00:20发布

问题:

I am trying to use the new Gmail API in a test Android Application. After much battling with the authorization progress I have discovered that specifically, The GoogleAuthUtil.getToken() method does not return a sufficient access token that can be used to access the Gmail API features (will return a 403 error when trying to do any action with the API). That said, the only way I did manage to receive a sufficient token is by doing the authentication process using a WebView and a (Installed application -> Other client ID on the API Console). So in one way it's a win win situation cause I can finally use the API, but the question that remains is what happens when the access token used for the API calls will expire or be compromised? Is there a way to receive a new token without popping out a consent screen? After all the User have already approved the application.

Many thanks.

EDIT: here's how you get a new token using a refresh token: Thanks to @Noam

        httpClient = new DefaultHttpClient();
        httpPost = new HttpPost(address);
        params.add(new BasicNameValuePair("refresh_token", token));
        params.add(new BasicNameValuePair("client_id", client_id));
        params.add(new BasicNameValuePair("client_secret", client_secret));
        params.add(new BasicNameValuePair("grant_type", "refresh_token"));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

回答1:

you can use GoogleAuthUtil.getToken() you just need to add the scope "https://www.googleapis.com/auth/gmail.readonly" with builder.addScope().