c# - 通过 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“未授权”状态代码。任何建议或指导将不胜感激,如果需要更多信息,我很乐意发布更多信息。谢谢!
更新:
解决方案
我没有看到Authorization
添加到请求的标头
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
就像在 cURL 示例中一样
Authorization
在发送之前设置请求
//...
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "{token-here}");
//...
推荐阅读
- python - Keras - 是否可以使用一个 GPU 同时训练两个不相关的模型?
- php - 在单个 HTTP POST 请求中同时传递文件资源和 json 正文
- gradle - 在 gradle 中,如何从 wsdl 生成库 jar 而不是生成源代码?
- javascript - 根据服务器中的值自动完成 html 块
- java - 如何解决 Spring Boot 应用程序中的 CORS 问题?
- android - 在颤动中找不到参数的方法 android()
- mysql-5.7 - mysql5.7.28无法设置innodb_directories
- kotlin - Micronaut http 客户端无法识别字段
- python - 当我将基本代码上传到 NodeMCU 时显示编译错误
- php - php用可选括号替换单词