[英]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.