2013-04-14 12 views
7

"サービスアカウント"の承認アクセスを使用してGoogle APIのいずれかを呼び出しようとしています。 Google APIコンソールの[サービス]タブで ".pk2"ファイルをダウンロードし、 "URL Shortener API"を有効にしました。 API(URL短縮またはAdsense)を呼び出そうとするたびに。私は次の例外を持っている -Google APIにアクセスすると無効な付与

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request 
{ 
    "error" : "invalid_grant" 
} 
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105) 
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:303) 
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:323) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:345) 
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:526) 
    at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:287) 
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:836) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463) 

以下のコードである - すべての「サービスアカウント」の

HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 
    JsonFactory JSON_FACTORY = new JacksonFactory(); 
    File privateKey = new File(ReportAdsense.class.getResource("mykey.p12").toURI()); 
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) 
      .setJsonFactory(JSON_FACTORY) 
      .setServiceAccountId("[email protected]") 
      .setServiceAccountScopes(UrlshortenerScopes.URLSHORTENER) 
      .setServiceAccountPrivateKeyFromP12File(privateKey) 
      .build(); 
    Urlshortener service = new Urlshortener.Builder(new NetHttpTransport(), JSON_FACTORY, null).setHttpRequestInitializer(credential).build(); 
    UrlHistory history = service.url().list().execute(); 

答えて

9

まず、それがユーザー認証を必要とするため、アドセンスのために動作しませんが。したがって、AdSenseの場合は、Oauth 2.0を使用する必要があります。初めてURL https://accounts.google.com/o/oauth2/tokenを使用して承認されたら、リフレッシュトークンをコピー&ペーストしてハードコードします。アクセストークンを取得するために使用するよりも、client_id、client_secret、およびrefresh_tokenを指定して新しいアクセストークンを取得することができます。これで、アプリケーションでアクセストークンを使用できるようになりました。

エラーに関して、私は同様の問題に直面しており、解決するのに多くの時間を費やしました。まず、有効なServiceAccountIdを使用していることを確認します。これは、「developer.gserviceaccount.com」で終了する電子メールを示します。 GoogleコンソールAPIでアカウントスコープと有効化されたサービスを指定したことを確認してください。

私のマシンでシステムクロックを同期させることでこの問題を解決しました。

回答がなくても同様のエラーのトピックがたくさんあります。さらに、一部の人々は、時にはそれが動作すること、時には無効な許可を返すと言っています。 1台のマシンで動作し、別のマシンで動作する可能性があります。私はそれがシステムクロックの問題かどうか分かりませんが、バグがあり、サポートが役に立たないようなので、サービスアカウントAPIを使わないでください

関連する問題