使用Google Natural Language API时PERMISSION_DENIED

时间:2016-09-23 16:33:54

标签: android google-cloud-platform

set up服务帐户并下载了凭证json文件。

GoogleNLSample-479e92642552.json

代码:

InputStream is = getAssets().open("GoogleNLSample-479e92642552.json");
GoogleCredential credential = GoogleCredential.fromStream(is).createScoped(CloudNaturalLanguageAPIScopes.all());
languageApi = new CloudNaturalLanguageAPI.Builder(new NetHttpTransport(),
                jacksonFactory, new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {
                })
                .setApplicationName(APPLICATION_NAME).build();

AnalyzeEntitiesRequest request =
                    new AnalyzeEntitiesRequest()
                            .setDocument(new Document().setContent(text).setType("PLAIN_TEXT").setLanguage("en"))
                            .setEncodingType("UTF8");
final CloudNaturalLanguageAPI.Documents.AnalyzeEntities analyze = languageApi.documents().analyzeEntities(request);

//Exception here
AnalyzeEntitiesResponse response = analyze.execute();

堆栈跟踪:

09-23 21:43:27.897 32562-677/com.sample.android W/System.err: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
09-23 21:43:27.897 32562-677/com.sample.android W/System.err: {
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:   "code" : 403,
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:   "errors" : [ {
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:     "domain" : "global",
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:     "message" : "The request cannot be identified with a client project. Please pass a valid API key with the request.",
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:     "reason" : "forbidden"
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:   } ],
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:   "message" : "The request cannot be identified with a client project. Please pass a valid API key with the request.",
09-23 21:43:27.897 32562-677/com.sample.android W/System.err:   "status" : "PERMISSION_DENIED"
09-23 21:43:27.897 32562-677/com.sample.android W/System.err: }

enter image description here

{
  "type": "service_account",
  "project_id": "***********",
  "private_key_id": "***********",
  "private_key": "-----BEGIN PRIVATE KEY-----\n***********\n-----END PRIVATE KEY-----\n",
  "client_email": "***********",
  "client_id": "***********",
  "auth_uri": "***********",
  "token_uri": "***********",
  "auth_provider_x509_cert_url": "***********",
  "client_x509_cert_url": "***********"
}

1 个答案:

答案 0 :(得分:2)

我建议您测试自然语言API here的快速入门步骤。更具体地说,您应首先确保:

  • 结算已启用
  • 自然语言API为enabled

使用curl完成一些测试后,您可以开始在Java进行实验。

但请注意,API密钥与服务帐户凭据之间存在差异。有关差异的详细说明,请参阅here。基本上,API密钥不在JSON文件中,它只是提供了与API交互的另一种/更简单的方法。

修改 正如@ archie-bpgc所指出的那样,初始化中也缺少一行:callback credential.initialize(request);