Reputation: 53
I have java code to connect to google drive using a service account, this works:
JsonFactory JSON_FACTORY = new GsonFactory();
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("sa.json"))
.createScoped(List.of(DriveScopes.DRIVE))
.createDelegated("[email protected]");
return new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, credential)
.setApplicationName("my-drive-app")
.build();
However i'm getting a deprecation warning that GoogleCredential
is deprecated and that i should use GoogleCredentials
(note the extra s at the end) from the google-auth-library
instead.
I can initialise GoogleCredentials
like this:
GoogleCredentials credential = GoogleCredentials.fromStream(new FileInputStream("sa.json"))
.createScoped(List.of(DriveScopes.DRIVE))
.createDelegated("[email protected]");
However I can't seem to figure out how to initialise the drive service using this new GoogleCredentials
object. Passing it in in place of the credential object gives a compiler error and all of the official google drive java documentation refers the now deprecated method.
Can someone tell me how to initialise google drive using the new credentials object?
Versions I'm using:
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-drive</artifactId>
<version>v3-rev20210919-1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.2.0</version>
</dependency>
Upvotes: 5
Views: 1794
Reputation: 26796
To connect to Google Drive use the HttpCredentialsAdapter to make the connection from GoogleCredentials
to GoogleCredential
.
Sample:
return new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, new HttpCredentialsAdapter(credential))
.setApplicationName("my-drive-app")
.build();
Upvotes: 5