无法通过HTTP请求在Unity C#中调用外部API(IBM Watson)?

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

我正在尝试调用IBM Watson的API来使用WWW库从我的Unity项目中执行情绪分析。这是我目前的代码:

string uri = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27";

WWWForm form = new WWWForm();
form.AddField ("text", "That%20was%20simply%20magnificent!");
form.AddField ("features", "sentiment");
form.AddField ("Content-Type", "application/json");
var headers = form.headers;
byte[] rawData = form.data;

headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(USERNAME + ":" + PASSWORD));

WWW www = new WWW(uri, rawData, headers);
yield return www;

其中USERNAMEPASSWORD是我的API凭据。但是,此代码一直给我415错误。此外,如果我将授权更改为身份验证,则错误更改为401。

我尝试使用hurl.it(有效)发出相同的请求,我打印出授权标题并将其与给定用户名和密码的hurl.it构造进行比较,它们是相同的字符串 - 但请求在项目中失败。我错过了什么?

c# rest http unity3d ibm-cloud
2个回答
1
投票

这应该适合你。

private IEnumerator CallNLU()
{
    string uri = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27";

    var headersDict = new Dictionary<string, string>();
    headersDict.Add("Content-Type", "application/json");
    headersDict.Add("Accept", "application/json");
    headersDict.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(USERNAME + ":" + PASSWORD)));

    string parameters = "{\"text\": \"Hello, welcome to IBM Watson!\", \"features\": {\"keywords\":{\"limit\":50}}}";
    byte[] rawData = Encoding.UTF8.GetBytes(parameters);

    WWW www = new WWW(uri, rawData, headersDict);
    yield return www;
    Debug.Log(www.text);
}

或者使用找到here的Watson Unity SDK。这是usage

private void Analyze()
{
  if (!_naturalLanguageUnderstanding.Analyze(OnAnalyze, OnFail, <parameters>))
      Log.Debug("ExampleNaturalLanguageUnderstanding.Analyze()", "Failed to get models.");
}

private void OnAnalyze(AnalysisResults resp, Dictionary<string, object> customData)
{
    Log.Debug("ExampleNaturalLanguageUnderstanding.OnAnalyze()", "AnalysisResults: {0}", customData["json"].ToString());
}

0
投票

您必须将正确的媒体类型添加到WWWForm,如下所示:

form.AddField("Content-Type", "application/x-www-form-urlencoded");

您应该检查Watson doc以查看哪一个是正确的,我想它将是Json

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