2013-04-14 3 views
7

"서비스 계정"승인 액세스를 사용하여 Google API를 호출하려고합니다. Google API 콘솔의 서비스 탭에서 ".pk2"파일을 다운로드하고 "URL Shortener API"를 활성화했습니다. 언제든지 API (URL 단축키 또는 애드 센스)를 호출하려고합니다. 나는 다음과 같은 예외를 가지고 -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

우선은 사용자 인증을 필요로하기 때문에, 애드 센스에 대해 작동하지 않습니다를. 그러므로 애드 센스의 경우 Oauth 2.0을 사용해야합니다. 처음으로 URL https://accounts.google.com/o/oauth2/token을 사용하여 권한을 부여받은 경우 새로 고침 토큰을 복사하여 붙여 넣기하고 하드 코드하십시오. 액세스 토큰을 얻는 데 사용할 수있는 것보다 client_id, client_secret 및 refresh_token을 지정하여 새 액세스 토큰을 얻을 수 있습니다. 이제 응용 프로그램에서 액세스 토큰을 사용할 수 있습니다.

오류에 관해서는 비슷한 문제에 직면 해 있으며 해결하는데 많은 시간이 걸렸습니다. 먼저 유효한 ServiceAccountId를 사용하고 있는지 확인하십시오. "developer.gserviceaccount.com"으로 끝나는 전자 메일을 가리켜 야합니다. Google Console API에서 계정 범위 및 활성화 된 서비스를 지정했는지 확인하십시오.

내 컴퓨터에서 시스템 시계를 동기화하여이 문제를 해결했습니다.

답변이없는 유사한 오류가있는 많은 주제가 있습니다. 더군다나 어떤 사람들은 때로는 효과가 있다고 말하며 때로는 무효 허가를 반환합니다. 그것은 하나의 기계에서 작동하고 다른 기계에서 실패 할 수 있습니다. 시스템 클럭 문제인지는 모르겠지만 서비스 계정 API 사용을 피할 것입니다. 버그가있는 것 같고 지원이 도움이되지 않습니다.

관련 문제