I set up服務帳戶並下載憑據json文件。PERMISSION_DENIED使用Google自然語言API
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": "***********"
}
只是爲了確認,你已經註冊你的APP在谷歌開發者控制檯?這個錯誤與您的API密鑰相關,所以或者您沒有發送您的密鑰或您的密鑰用於另一個API –
@LucasQueirozRibeiro我註冊了API密鑰,但在哪裏使用它?檢查有問題的屏幕截圖。謝謝。 –
我從來沒有專門使用這個API,但我想你是從Json('GoogleCredential.fromStream(is)')獲取你的api。在其他API中,我聲明清單中的鍵爲'元數據',客戶自動選擇如下:'mGoogleApiClient = new GoogleApiClient.Builder(getContext()) .addApi(Places.GEO_DATA_API) .build() ;' –