我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": "***********"
}