简体   繁体   中英

com.google.api.client.googleapis.auth.oauth2.GoogleCredential is now deprecated

Google's sample code for the vision API shows this:

  public static Vision getVisionService() throws IOException, GeneralSecurityException {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
  }

But com.google.api.client.googleapis.auth.oauth2.GoogleCredential is now deprecated. What is the correct way to authenticate the above now?

You can do this a couple ways.

Option 1:

  1. Follow the steps on this quickstart page
  2. Set GOOGLE_APPLICATION_CREDENTIALS which is something the client library uses by default

Option 2:

  1. Load the service key file yourself.
// imports
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;

import java.io.FileInputStream;

// somewhere in your code, load the credentials
try {
  Credentials credentials = GoogleCredentials.fromStream(
        new FileInputStream("path_to_file.json"));

  FixedCredentialsProvider fixedCredentialsProvider =
        FixedCredentialsProvider.create(credentials);

  ImageAnnotatorSettings settings = 
        ImageAnnotatorSettings.newBuilder()
           .setCredentialsProvider(
               fixedCredentialsProvider).build();

  ImageAnnotatorClient client = 
        ImageAnnotatorClient.create(settings);
catch(IOException e) {
  e.printStackTrace(e);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM