【问题标题】:Unable to call external API (IBM Watson) in Unity C# via HTTP request?无法通过 HTTP 请求在 Unity C# 中调用外部 API (IBM Watson)?
【发布时间】:2017-12-31 15:32:58
【问题描述】:

我正在尝试调用 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


【解决方案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());
}

【讨论】:

    【解决方案2】:

    您必须像这样向 WWWForm 添加正确的媒体类型:

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

    你应该检查 Watson 文档,看看哪个是正确的,我想它会是 Json

    【讨论】:

    • @Technicolor 401 还是 415?
    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 2017-02-12
    • 1970-01-01
    • 2015-06-14
    • 2019-08-08
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    相关资源
    最近更新 更多