1
votes

I am following this tutorial Hello Analytics API: Java quickstart for service accounts. The code works fine. The problem is that the code below is using the p12 key file Google is only supporting them for backwards compatibility they have started encouraging developers to use the JSon Key file for service accounts.

// Construct a GoogleCredential object with the service account email
// and p12 file downloaded from the developer console.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(httpTransport)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
    .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
    .setServiceAccountScopes(AnalyticsScopes.all())
    .build();

I have searched high and low i cant find an example of using the JSon key file with the Google APIs Java library. I even checked the documentation and its not listed GoogleCredential.Builder but i am unsure if this documentation is even up to date. I tried to check the code in the library but i am quite new to Java and was not able to find anything of use Google api java client

Is it possible to use the Json Key File with service accounts in the Google APIs Java client library?

1

1 Answers

2
votes

Just use fromStream method.

File jsonKey = new File(KEY_FILE);
InputStream inputStream = new FileInputStream(jsonKey);
GoogleCredential credential =
    GoogleCredential.fromStream(inputStream, HTTP_TRANSPORT, JSON_FACTORY);