![](/img/trans.png)
[英]Google Dialogflow: The Application Default Credentials are not available
[英]GCP DialogFlow API error: "The Application Default Credentials are not available"
嘗試在 Spring 應用程序中使用 Google DialogFlow API 時出現以下錯誤:
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
我成功執行了https://cloud.google.com/dialogflow/es/docs/quick/setup#windows中的所有步驟,並且當我運行命令gcloud auth application-default print-access-token
來測試身份驗證,它工作正常。 但是,在我的 spring 應用程序中,我在嘗試使用 API 時不斷收到錯誤消息。 作為參考,我使用以下內容將我的 Spring 應用程序連接到 DialogFlow API: https ://cloud.google.com/dialogflow/es/docs/quick/api#detect-intent-text-java
有什么建議嗎?
編輯:我手動將 GOOGLE_APPLICATION_CREDENTIALS 添加為環境變量,但現在出現以下錯誤:
java.lang.NoSuchMethodError: 'com.google.auth.oauth2.ServiceAccountCredentials com.google.auth.oauth2.ServiceAccountCredentials.createWithUseJwtAccessWithScope(boolean)'
添加此代碼塊作為DetectIntentTexts
類中的主要方法。
public static void main(String[] args) {
List <String> myArr = new ArrayList<String>();
myArr.add("Tell me your name");
try{
detectIntentTexts("project-id",myArr,"123","en-us");
}
catch(Exception e){}
}
將此代碼放入您的detectIntentTexts
方法中。
String jsonPath = "<your_json_file_path>";
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
SessionsSettings sessionsSettings =
SessionsSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credentials))
.build();
SessionsClient sessionsClient = SessionsClient.create(sessionsSettings);
另外,替換此代碼:
try (SessionsClient sessionsClient = SessionsClient.create())
與此try (SessionsClient client = SessionsClient.create(sessionsSettings))
將這些包導入您的班級。
import java.util.ArrayList;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import com.google.common.collect.Lists;
import com.google.cloud.dialogflow.v2.SessionsSettings;
import com.google.api.gax.core.FixedCredentialsProvider;
最后,將這些依賴項添加到您的pom.xml
中。
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.google.api</groupId>
<artifactId>gax</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.google.api</groupId>
<artifactId>gax-grpc</artifactId>
<version>2.8.1</version>
</dependency>
這是輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.