c# - C# 中的 IBM Watson Tone Analyzer API 调用
问题描述
我试图在 C# 中编写对 watson 音调分析器服务的 post API 调用。似乎验证用户的方式最近从用户名和密码更改为 api 密钥。
我试图通过“授权”标头或通过名为“apikey”的标头传递 apikey。在这两种情况下,我都收到错误 401 Unauthorized.. 我使用的另一个标头是 Content-Type 设置为 application/json ..
此调用不适用于 .net 项目或邮递员。
如何使用 C# 发送 API 请求,如何通过 shell 传递 api 密钥,以及应该使用哪些标头?
这是我尝试的代码(此代码返回内部服务器错误 500 的错误,而我使用邮递员进行的测试返回 401 Unauthorized):
HttpClient client = new HttpClient();
string baseURL;
string apikey= "****************";
baseURL = "https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21";
string postData = "{\"text\": \"" + "hi hello" + "\"}";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apikey", apikey);
var response = client.PostAsync(baseURL, new StringContent(postData, Encoding.UTF8, "application/json")).Result;
Console.WriteLine(response);
我收到的错误:
StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Mime-Version: 1.0
Connection: close
Date: Sun, 17 Feb 2019 11:37:53 GMT
Server: AkamaiGHost
Content-Length: 177
Content-Type: text/html
Expires: Sun, 17 Feb 2019 11:37:53 GMT
}
解决方案
为此,您需要进行适当的基本授权(请参阅https://cloud.ibm.com/apidocs/tone-analyzer上的授权部分)。根据RFC 7617基本授权意味着授权方案是Basic
,授权参数是用户名:Base64 编码的密码。
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("apikey:" + apikey)));
以下代码对我有用:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("apikey:" + apikey)));
string postData = "{\"text\": \"" + "I am happy it finally worked" + "\"}";
var response = client.PostAsync("https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21", new StringContent(postData, Encoding.UTF8, "application/json")).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
哪个返回{"document_tone":{"tones":[{"score":0.956143,"tone_id":"joy","tone_name":"Joy"},{"score":0.620279,"tone_id":"analytical","tone_name":"Analytical"}]}}
。
附带说明一下,我最初使用的是法兰克福网关(gateway-fra),当我在伦敦网关(gateway-lon)上使用我的 apikey 时,我还收到了服务器错误 500(内部服务器错误)。对于其他网关,我收到错误 401(未经授权),因为 apikey 似乎是每个服务和网关/位置的。在我删除了我的 ToneAnalyzer 服务并这次为伦敦网关设置了一个新服务后,它就可以工作了。所以我想,当您在另一个网关上使用一个网关的 apikey 时,IBM 的授权服务器或他们使用的 Akamai 负载均衡器有点不稳定。
推荐阅读
- c# - 按下 ctrl+space 时不要触发单击焦点元素
- r - source() 相对于当前脚本目录的路径?
- java - Java + UDP + DatagramSocket:当 UDP 设计为无连接时,为什么会抛出 PortUnreachableException?
- docker - Traefik docker 默认域配置
- twilio - 德语交互式语音响应
- wso2 - 带有声明的 WSO2(5.8 版)的多实例问题
- javascript - 如何使用请求映射修复 thymleaf 错误?
- html - 下拉菜单有效,但仅当我悬停而不单击时
- jenkins - 检查是否存在另一个管道
- javascript - 如何处理从 JavaScript 模块导入的动态对象?