Alphabet Google API SDK
综述
SDK
- SDK Credential
-
public static boolean credential(List
scopes) { // 控制台需启用对应“API和服务”项;无范围应指定默认范围“../cloud-platform”。 var scopes = Arrays.asList("https://www.googleapis.com/auth/cloud-platform"); // 可选方法 createDelegated(...) 只用于 Google Workspace。 return GoogleCredential.fromStream(new FileInputStream("D:\\sa.json")) .createDelegated("google_workspace@domain.name").createScoped(scopes); } Java 本地测试 Google API 接口 OAuth2 验证实例: // implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' GCP -> 凭据 -> OAuth 客户端 ID -> 桌面应用 // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2?hl=zh-cn#installed_applications private static Credential auth() throws IOException, GeneralSecurityException { var JSON_FACTORY = GsonFactory.getDefaultInstance(); var cs = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(new FileInputStream("D:\\temp\\client_secret_11111111111-xxx.apps.googleusercontent.com.json"))); var flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, cs, List.of("https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube")) .setDataStoreFactory(new FileDataStoreFactory(new File(System.getProperty("user.home"), ".store/x/"))).build(); var c = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); System.out.println(c.getAccessToken()); return c; // Token有效期为1个小时。 } - People SDK
-
var scopes = Arrays.asList(PeopleServiceScopes.CONTACTS_READONLY); var s = new PeopleService.Builder(GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), credential(scopes)).build(); var r = s.people().connections().list("people/me").setPageSize(100) .setPersonFields("names,emailAddresses,phoneNumbers").execute();
API
Google API Explorer 支持API keys的服务:Cloud Vision API(免费千次)、Calendar API(免费)、Firebase API(免费)、Maps API、Gemini API(免费/Vertex AI Gemini API不支持)、Cloud Natural Language API 如果所处环境为 GCE 和 GAE ,可直接获取 access_token credential: curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" \ -H "Metadata-Flavor: Google" fetch("https://content-vision.googleapis.com/v1/images:annotate?alt=json&key=[ApiKey]", { "method": "POST", "headers": { "content-type": "application/json" }, "body": `{"requests":[{"features":[{"type":"TEXT_DETECTION"}],"image":{"source":{"imageUri":"gs://cloud-samples-data/vision/ocr/sign.jpg"}}}]}` }); curl "https://language.googleapis.com/v1/documents:analyzeEntities" \ -X POST \ -H "X-Goog-Api-Key: $GOOGLE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"document":{"content":"The rain in Spain stays mainly in the plain.", "type":"PLAIN_TEXT"}}' \ -i