C#中的IBM Watson Tone Analyzer API调用

问题描述 投票:0回答:1

我试图在C#中编写一个对Watson音调分析器服务的后API调用。似乎验证用户的方式最近从用户名和密码更改为api密钥。

我试图通过“授权”标题或通过名为“apikey”的标题传递apikey。在这两种情况下我都收到错误401 Unauthorized ..我使用的另一个标题是Content-Type设置为application / json ..

此调用在.net项目或邮递员中不起作用。

如何使用C#发送API请求,shell如何传递api密钥,以及我应该使用哪些标头?

这是我尝试的代码(此代码返回内部服务器错误500的错误,而我对postman执行的测试返回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
}
c# api ibm-cloud ibm-watson
1个回答
1
投票

为此,您需要进行适当的基本授权(请参阅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(未授权),因为apikeys似乎是每个服务和网关/位置。在我删除了ToneAnalyzer服务并为伦敦网关设置了一个新服务之后,它运行了。所以我猜,当你在另一个网关上使用apikey作为一个网关时,IBM的授权服务器或他们使用的Akamai负载均衡器有点不稳定。

© www.soinside.com 2019 - 2024. All rights reserved.