我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: }
{
"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": "***********"
}
最佳答案
我建议测试自然语言apihere的快速启动步骤。更具体地说,你应该首先确保:
已启用计费
自然语言apienabled
在对curl进行了一些测试之后,可以开始在Java中进行实验。
但是,请注意,api密钥和服务帐户凭据之间存在差异。有关差异的深入解释,请参见here。基本上,api密钥不在json文件中,它只是提供了与api交互的另一种/更简单的方式。
编辑:
正如@archie bpgc所指出的,initialize:callbackcredential.initialize(request);