【问题标题】:Receiving 401 "Unauthorized" error while using Google Cloud AutoML via HttpClient通过 HttpClient 使用 Google Cloud AutoML 时收到 401“未授权”错误
【发布时间】:2019-03-21 05:12:29
【问题描述】:

我正在使用 C# 编写一个 WPF 应用程序,它尝试使用 HttpClient 进行 Google Cloud AutoML API 调用。我能够与服务器取得联系,但总是得到“未经授权”的响应。我已经搜索了 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“未授权”状态代码。任何建议或指导将不胜感激,如果需要更多信息,我很乐意发布更多信息。谢谢!

更新:

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

【问题讨论】:

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

标签: c# json authorization http-status-code-401 google-cloud-automl


【解决方案1】:

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

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

就像在 cURL 示例中一样

在发送请求前设置Authorization

//...

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

//...

【讨论】:

  • 谢谢 Nkosi,但在添加您建议的更改后,我仍然得到相同的 401 响应状态代码。这可能是由我使用的实际令牌引起的吗?我在 Google Cloud 控制台中使用命令 gcloud application-default print-access-token 生成了它,所以我认为这里只需要复制粘贴操作。
猜你喜欢
  • 2020-12-23
  • 2023-03-27
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 2019-07-06
相关资源
最近更新 更多