2012-11-06 73 views
5

我想根據保存在數據庫中的「刷新令牌」獲取新的「訪問令牌」。(JAVA)Google API分析 - 無法使用「刷新令牌」獲取新的「訪問令牌」

這裏是我寫的代碼:

GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder() 
     .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) 
     .setClientSecrets(CLIENT_ID, CLIENT_SECRET); 
credentialBuilder.addRefreshListener(new MyCredentialRefreshListener()); 

credential = credentialBuilder.build(); 
credential.setRefreshToken("saved_refresh_token_from_database"); 

try { 
    credential.refreshToken(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 


class MyCredentialRefreshListener implements CredentialRefreshListener { 
    public void onTokenResponse(Credential cr, TokenResponse tr) { 
     System.out.println("Credential was refreshed successfully."); 
    } 

    public void onTokenErrorResponse(Credential cr, TokenErrorResponse tr) { 
     System.out.println(tr); 
    } 
} 

我得到這個消息:

com.google.api.client.auth.oauth2.TokenResponseException:400錯誤

請求{「error」:「invalid_grant」}

我使用相同的CLIENT_ID,CLIE NT_SECRET和「刷新令牌」在一個PHP腳本和那裏我設法獲得新的「訪問令牌」使用「刷新令牌」時,「訪問令牌」過期。

我寫的代碼基於javadoc.google-oauth-java-client

這裏的任何人都知道如何修改代碼來獲取新的訪問令牌?

在此先感謝。

更新:問題是我在數據庫中保存了refresh_token而沒有對其執行json_decode,它包含一個「\」,它被認爲是JSON中的轉義字符。

+0

我試過你的代碼,它爲我工作。我認爲這是刷新令牌的數據/格式問題。 – user1697575

回答

2

看起來你可能已經發現了一些過時的文檔。您鏈接的JavaDoc用於客戶端庫的1.8版本。目前的版本是1.12。

客戶端庫作者建議您使用GoogleAuthorizationCodeFlow來管理您的OAuth憑據。它會自動處理刷新。如果按照此路徑,代碼將如下所示:

// Create the flow 
AuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
    new UrlFetchTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, 
    Collections.singleton(OAUTH_SCOPES)) 
    .setAccessType("offline") 
    .setCredentialStore(new AppEngineCredentialStore()) 
    .build(); 

// User Id: e.g. from session 
Credential credential = authorizationCodeFlow.loadCredential(USER_ID);  

// Make your API call. This example uses the Google+ API 
// If the access token has expired, it will automatically refresh 
Plus plus = new Plus(new UrlFetchTransport(), new JacksonFactory(), credential) 
    .activities().list("me", "public").execute(); 
1

如果您獲取http狀態400,並顯示消息「invalid_grant」。 我想你應該檢查你的實例HTTP_TRANSPORT,JSON_FACTORY,CLIENT_ID,CLIENT_SECRET