java - 找不到 GOOGLE_APPLICATION_CREDENTIALS
问题描述
目前必须将 Google Cloud Platform 服务集成到我的应用中,但收到以下异常:
**W/System.err: 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.
at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
W/System.err: at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:119)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:91)
at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:67)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:135)
at com.google.cloud.speech.v1.stub.GrpcSpeechStub.create(GrpcSpeechStub.java:94)
at com.google.cloud.speech.v1.stub.SpeechStubSettings.createStub(SpeechStubSettings.java:131)
at com.google.cloud.speech.v1.SpeechClient.<init>(SpeechClient.java:144)
at com.google.cloud.speech.v1.SpeechClient.create(SpeechClient.java:126)
at com.google.cloud.speech.v1.SpeechClient.create(SpeechClient.java:118)
at com.dno.app.ui.TranscriptFragment$1.onClick(TranscriptFragment.java:72)**
设置环境变量:
.json 文件在这里:
应用程序在此代码块(片段)中的 authImplicit() 处崩溃:
transcriptBtn = getActivity().findViewById(R.id.transcript_button);
transcriptBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try (SpeechClient speechClient = SpeechClient.create()) {
authImplicit(); // issue with Google Platform Login Authentification
// - does not read the environment variable, and therefore cannot get access to the .json file.
// The path to the audio file to transcribe
String fileName = getFile().getName();
// Reads the audio file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString audioBytes = ByteString.copyFrom(data);
// Builds the sync recognize request
RecognitionConfig config =
RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.FLAC)
.setSampleRateHertz(16000)
.setLanguageCode("en-US")
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
// Performs speech recognition on the audio file
RecognizeResponse response = speechClient.recognize(config, audio);
List<SpeechRecognitionResult> results = response.getResultsList();
for (SpeechRecognitionResult result : results) {
// There can be several alternative transcripts for a given chunk of speech. Just use the
// first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
authImplicit() 的代码:
private void authImplicit() {
// If you don't specify credentials when constructing the client, the client library will
// look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
Storage storage = StorageOptions.getDefaultInstance().getService();
System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
}
我选择了所有者类型的服务帐户,因此我不应该缺少任何权限。
编辑(仍然无法正常工作):我尝试使用此示例,但仍然无法正常工作:应用程序默认凭据不可用
编辑#2(在服务器端工作):事实证明,谷歌目前不支持 Android 来完成这项任务。此后,我将代码移至 ASP.NET 后端,现在代码运行顺畅。
感谢您提供以下帮助。
解决方案
我可以理解您已阅读文档并实施了此处所述的所有步骤 - https://cloud.google.com/storage/docs/reference/libraries#windows
正如@John Hanley 提到的,您是否检查了打印环境变量?
正如异常所说,它绝对不是与所有者相关的权限问题
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.
现在,要解决这个问题,您是否只想使用环境变量?还是其他方法都可以?
如果您对其他方法没问题,请查看此代码
private void authImplicit() {
//please give exact file name for this credentials.json
Credentials credentials = GoogleCredentials
.fromStream(new FileInputStream("C:\\Users\\dbgno\\Keys\\credentials.json"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials)
.setProjectId("Some Project").build().getService();
System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
}
编辑 1:致力于解决方案 试试这个,看看您是否可以读取您作为输入提供的 JSON 文件。打印语句应显示您打算使用的服务帐户进行身份验证
public static Credential getDriveService(String fileLocation, String servAccAdmin)
throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential googleCredential =
GoogleCredential.fromStream(new FileInputStream(fileLocation), httpTransport, jsonFactory)
.createScoped(SCOPES);
System.out.println("--------------- " + googleCredential.getServiceAccountId());
Credential credential = new GoogleCredential.Builder()
.setTransport(googleCredential.getTransport())
.setJsonFactory(googleCredential.getJsonFactory())
.setServiceAccountPrivateKeyId(googleCredential.getServiceAccountPrivateKeyId())
.setServiceAccountId(googleCredential.getServiceAccountId()).setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKey(googleCredential.getServiceAccountPrivateKey())
.setServiceAccountUser(servAccAdmin).build();
return credential;
}
编辑2:
当我们看到一些凭证问题时,我正在尝试查看我访问任何其他 google API 服务的方式,可能是驱动器或 gmail,我们手动传递密钥文件并构建凭证,并且这些凭证应该用于进一步的服务调用. 现在尝试添加这些依赖项,这只是通过使用我们访问 google drive/gmail 等的相同方式进行故障排除。我们将了解 google cloud api 是否能够构建凭证
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>${project.http.version}</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>${project.http.version}</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>${project.oauth.version}</version>
</dependency>
推荐阅读
- spring - 在具有 1 个 web.xml 文件的单个 tomcat 实例中运行 spring mvc web 应用程序和 jaxws soap web 服务
- javascript - Terra.js (wasm.ContractQuery) 有错误状态代码 500
- python - VSCode 编译器打印加法语句而不是编译它
- javascript - 重定向没有在本地存储中保存价值
- java - Tomcat 的 Catalina 实用程序线程定期使用高 CPU 和内存
- python - python脚本调用shell脚本,即使python脚本结束,我也想保持其进程处于活动状态
- wordpress - 将新资源属性“order_id”添加到 woocommerce 产品类别 rest api
- replace - 如何用小写字母替换大写字母?
- sql - Bigquery SQL - 排除当前财政年度的行/数据
- java - 更改活动时如何回到上一个片段?