首页 > 解决方案 > 通过 HttpClient 使用 Google Cloud AutoML 时收到 401“未授权”错误

问题描述

我正在使用 C# 编写一个 WPF 应用程序,该应用程序尝试使用HttpClient. 我能够与服务器取得联系,但总是得到“未经授权”的响应。我已经搜索了 StackOverflow 和 AutoML 文档以获取有关如何正确地将“CURL”请求转换为简单的 HTTP 请求的任何提示,我可以在我的 C# 应用程序中以编程方式执行该请求,但还没有找到任何提供足够指导的内容点(因此我的问题)。

这是我在建模 HTTP 请求之后的 CURL 请求:

curl -X POST -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/MyProjectId:predict -d @request.json

此请求的某些元素我无法弄清楚如何翻译成 C#,即Authorization: Bearer组件。我是否需要以某种方式找到一个令牌并将其添加到标题或其他内容中?如果是这样,我如何以字符串形式获取此令牌?这似乎是我真正坚持的。

这是到目前为止我实际拥有的 C# 代码。

public async Task<object> GetPrediction(string imagePath)
{
    string apiKey = "MyApiKey";
    string projectId = "MyProjectId";

    HttpResponseMessage response;
    byte[] img = File.ReadAllBytes(imagePath);

    string jsonBody = "{\"payload\":{\"image\":{\"imageBytes\":\"" + Encoding.UTF8.GetString(imgBody) + "\"}}}";
    string uri = $"https://automl.googleapis.com/v1beta1/projects/image-object-detection/locations/us-central1/models/{projectId}:predict?key={apiKey}";
    string token = “MyToken”;

    var client = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Post, uri);
    request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
    request.Headers.Authorization = new AuthenticarionHeaderValue(“Bearer”, token);
    request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

    response = await client.SendAsync(request);

    return Task.FromResult(response);                  
}

这段代码基本上可以联系,然后我得到一个 401“未授权”状态代码。任何建议或指导将不胜感激,如果需要更多信息,我很乐意发布更多信息。谢谢!

更新:

我修改了代码块以包含来自Nkosi的建议更改,但我仍然看到相同的 401 状态代码。

标签: c#jsonauthorizationhttp-status-code-401google-cloud-automl

解决方案


我没有看到Authorization添加到请求的标头

-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"

就像在 cURL 示例中一样

Authorization在发送之前设置请求

//...

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "{token-here}");

//...

推荐阅读