Googleスプレッドシートにアクセスするためのoauth2認証にJavaライブラリを使用しています。
OAuth2 認証に以下のコードを使用しています。
credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
.setServiceAccountScopes("https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds")
.setServiceAccountPrivateKeyFromP12File(new File("xxxxx-privatekey.p12")).build();
「資格情報」を取得した後、以下のコードを使用してスプレッドシートを読み取ります。
SpreadsheetService service = new SpreadsheetService(
"MySpreadsheetIntegration");
service.setOAuth2Credentials(credential);
URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
System.out.println(feed.getTotalResults());
上記のコードを実行すると、合計結果が 0 になります。
私が使用する場合:
service.setUserCredentials("email", "password");
oauth2 認証の代わりに、正しい結果が返されます。OAuth2 認証の何が問題なのかわかりません。また、「資格情報」オブジェクトから「アクセストークン」を出力すると、有効なアクセストークンが出力されます。