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

无法连接Gemini/Vertex AI:两种代码方案均触发HTTP错误求助

无法连接Gemini/Vertex AI:401未授权与404 gRPC错误排查求助

已确认的前提条件

  • 已启用Gemini和Vertex AI APIs
  • 拥有Cloud控制台「owner」和「Vertex AI user」角色
  • API key无使用限制,且已正确设置GOOGLE_APPLICATION_CREDENTIALS环境变量
  • 确认URL中的project ID、API key无拼写错误
  • 通过Cloud SDK获取可用区域列表并尝试多个location参数(如europe-west1),问题未解决

两种代码尝试及错误

共用变量

private static readonly string projectId = "xxxx";
private static readonly string location = "europe-west1"; // 已尝试多个区域
private static readonly string geminiApiKey = "xxxx";
private static readonly string url = $"https://{location}-aiplatform.googleapis.com/v1/projects/{projectId}/locations/{location}/publishers/google/models/gemini-pro:generateContent";

尝试1:返回HTTP 401「unauthorised」

// attempt 1 - results in HTTP 401 "unauthorised" 

var content = new StringContent(CreateTextRequestBody(text), Encoding.UTF8, "application/json");
var client = new HttpClient();

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", geminiApiKey);

var response = await client.PostAsync(url, content);

if (response.IsSuccessStatusCode)
{
      string responseContent = await response.Content.ReadAsStringAsync();
      // Parse the JSON response to get the generated text
      return responseContent;
}
else
{
      throw new Exception($"Gemini request error: {response.StatusCode} {response.ReasonPhrase}");
}

尝试2:返回HTTP 404「Bad gRPC response.」

// attempt 2 - results in HTTP 404 "Bad gRPC response." 

var instance = new Google.Protobuf.WellKnownTypes.Value
{
     StructValue = new Struct
     {
         Fields =
         {
             { "input_text", Google.Protobuf.WellKnownTypes.Value.ForString("Hello, world!") }
         }
     }
};

// Convert instance to a list of values
var instances = new List<Google.Protobuf.WellKnownTypes.Value> { instance };

// Optional: Additional parameters for prediction
var parameters = new Google.Protobuf.WellKnownTypes.Value
{
    StructValue = new Struct
    {
        Fields =
        {
            { "param_key", Google.Protobuf.WellKnownTypes.Value.ForString("param_value") }
        }
    }
};

try
{
    // Making the predict request
    PredictResponse response = predictionClient.Predict(url, instances, parameters);

    // Print the response
    foreach (var prediction in response.Predictions)
    {
        Debug.WriteLine($"Prediction: {prediction}");
    }
}
catch (Grpc.Core.RpcException e)
{
    Debug.WriteLine($"RPC failed: {e.Status}");
}

问题定位与修复方案

针对尝试1的401错误

API Key不能使用Bearer认证方式,Bearer是OAuth2令牌的专属认证头,API Key需改用X-Goog-Api-Key请求头,或追加到URL参数中:

方案1:使用X-Goog-Api-Key请求头

var content = new StringContent(CreateTextRequestBody(text), Encoding.UTF8, "application/json");
var client = new HttpClient();

// 替换Bearer认证为API Key专属头
client.DefaultRequestHeaders.Add("X-Goog-Api-Key", geminiApiKey);

var response = await client.PostAsync(url, content);

// 后续逻辑不变

方案2:在URL中追加key参数

修改url变量:

private static readonly string url = $"https://{location}-aiplatform.googleapis.com/v1/projects/{projectId}/locations/{location}/publishers/google/models/gemini-pro:generateContent?key={geminiApiKey}";

同时删除代码中设置Authorization头的逻辑。

针对尝试2的404错误

  1. 端点与接口不匹配:Predict方法是旧模型的预测接口,Gemini Pro需使用GenerateContent接口;手动构造gRPC请求易出错,建议直接使用官方SDK。
  2. 推荐修复:使用官方.NET SDK
    安装Google.Cloud.AIPlatform.V1 NuGet包后,使用以下代码:
using Google.Cloud.AIPlatform.V1;
using Google.Protobuf.WellKnownTypes;

// 自动读取GOOGLE_APPLICATION_CREDENTIALS环境变量完成认证
var client = new PredictionServiceClientBuilder
{
    Endpoint = $"{location}-aiplatform.googleapis.com"
}.Build();

var content = new Content
{
    Parts = { new Part { Text = "Hello, world!" } }
};

var request = new GenerateContentRequest
{
    Model = $"projects/{projectId}/locations/{location}/publishers/google/models/gemini-pro",
    Content = content
};

var response = client.GenerateContent(request);
Console.WriteLine(response.Candidates[0].Content.Parts[0].Text);

Location参数验证

执行以下gcloud命令确认Gemini Pro支持的区域:

gcloud ai models list --region=global

输出中会显示可用区域(如us-central1、europe-west4),优先选择这些区域测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:44:54