代码之家  ›  专栏  ›  技术社区  ›  Pic Mickael

C#IBM Speech to Text使用APIKey获取令牌

  •  -1
  • Pic Mickael  · 技术社区  · 7 年前

    基于 https://gist.github.com/nfriedly/0240e862901474a9447a600e5795d500 , 我正在尝试使用WebSocket来使用IBM语音到文本API。 看起来现在IBM不再提供用户名/密码了。 只有api密钥。

    ibmdoc似乎也不是最新的,因为他们的示例使用带有用户名和密码的CURL https://console.bluemix.net/docs/services/speech-to-text/getting-started.html#getting-started-tutorial

    但这不起作用,因为我从服务器上得到一个未经授权的错误。

    也许我读错了,我应该传递一个令牌而不是密码。

    我可以使用HttpClient毫无问题地获得令牌。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Pic Mickael    7 年前

    在一些帮助下,我终于找到了如何用apiKey处理WebSocket。

    我把代码贴在这里以防别人需要

    IamTokenData GetIAMToken(string apikey)
    {
      var wr = (HttpWebRequest)WebRequest.Create("https://iam.bluemix.net/identity/token");
      wr.Proxy = null;
      wr.Method = "POST";
      wr.Accept = "application/json";
      wr.ContentType = "application/x-www-form-urlencoded";
    
      using (TextWriter tw = new StreamWriter(wr.GetRequestStream()))
      {
        tw.Write($"grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey={apikey}");
      }
      var resp = wr.GetResponse();
      using (TextReader tr = new StreamReader(resp.GetResponseStream()))
      {
        var s = tr.ReadToEnd();
        return JsonConvert.DeserializeObject<IamTokenData>(s);
      }
    }
    
    IamTokenData tokenData = GetIAMToken([Your IamApiKey]);
    
    CancellationTokenSource cts = new CancellationTokenSource();
    
    ClientWebSocket clientWebSocket = new ClientWebSocket();
    
    clientWebSocket.Options.Proxy = null;
    clientWebSocket.Options.SetRequestHeader("Authorization", $"Bearer {token.AccessToken}");
    
    // Make the sure the following URL is that one IBM pointed you to
    Uri connection = new Uri($"wss://gateway-wdc.watsonplatform.net/speech-to-text/api/v1/recognize");
    try
    {
      //await clientWebSocket.ConnectAsync(connection, cts.Token);
      clientWebSocket.ConnectAsync(connection, cts.Token).GetAwaiter().GetResult();
      Console.WriteLine("Connected!");
    }
    catch (Exception e)
    {
      Console.WriteLine("Failed to connect: " + e.ToString());
      return null;
    }
    
    // ... Do what you need with the websocket after that ...