You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次使用Google Natural Language API遇异常,求解决方案

解决Google Natural Language API的Application Default Credentials异常

这个问题我本地调试Google API时也踩过坑,本质就是Google Cloud API需要验证你的身份权限,而本地环境不会自动提供默认凭证,所以才抛出这个错误。按下面的步骤一步步来就能解决:

步骤1:获取服务账号密钥文件

  • 登录Google Cloud控制台,找到你正在使用的项目
  • 进入「IAM与管理」→「服务账号」页面
  • 新建一个服务账号(或选择已有服务账号),给它分配「Cloud Natural Language API 使用者」的权限
  • 点击该服务账号的「密钥」标签,选择「添加密钥」→「创建新密钥」,密钥类型选JSON,下载后保存到本地安全的路径,比如命名为nl-api-key.json

步骤2:配置环境变量(推荐生产/正式环境使用)

根据你的操作系统设置环境变量:

  • Windows:打开命令提示符,执行以下命令(替换为你的密钥文件实际路径)
    setx GOOGLE_APPLICATION_CREDENTIALS "C:\Users\YourName\Documents\nl-api-key.json"
    
    执行完后重启你的IDE或命令行窗口,让环境变量生效。
  • macOS/Linux:打开终端,执行临时生效的命令:
    export GOOGLE_APPLICATION_CREDENTIALS="/home/yourname/Documents/nl-api-key.json"
    
    如果想永久生效,把上面的命令添加到~/.bashrc(或~/.zshrc,取决于你用的shell)文件末尾,然后执行source ~/.bashrc让配置立即生效。

步骤3:代码中直接指定密钥(适合快速测试)

如果不想配置环境变量,也可以在代码里直接加载密钥文件,修改你的客户端创建代码:

using Google.Cloud.Language.V1;
using Google.Apis.Auth.OAuth2;
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            string text = "Hello World!";
            try
            {
                // 加载本地密钥文件
                var credential = GoogleCredential.FromFile("path/to/your/nl-api-key.json");
                // 用凭证构建客户端
                var client = new LanguageServiceClientBuilder { Credential = credential }.Build();
                
                var response = client.AnalyzeSentiment(new Document()
                {
                    Content = text,
                    Type = Document.Types.Type.PlainText
                });
                var sentiment = response.DocumentSentiment;
                Console.WriteLine($"Score: {sentiment.Score}");
                Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

补充说明

Google的客户端库会自动查找「应用默认凭证」,在Google Compute Engine、Cloud Run等Google托管环境中,系统会自动提供这些凭证,但本地开发时必须手动配置——要么通过环境变量,要么代码指定,这两种方式都是告诉客户端库“用这个身份来访问API”。

内容的提问来源于stack exchange,提问作者progr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:37:26