无法检测内容输入的语言,错误401

时间:2019-01-29 08:50:13

标签: c# httprequest system.net

无法检测内容输入的语言。

我已经仔细检查了API密钥,它是正确的。 当我尝试检测语言时,出现错误401。

    // ***** DETECT LANGUAGE OF TEXT TO BE TRANSLATED
    private string DetectLanguage(string text)
    {
        string uri = TEXT_ANALYTICS_API_ENDPOINT + "languages?numberOfLanguagesToDetect=1";

        // create request to Text Analytics API
        HttpWebRequest detectLanguageWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        detectLanguageWebRequest.Headers.Add("Ocp-Apim-Subscription-Key", TEXT_ANALYTICS_API_SUBSCRIPTION_KEY);
        detectLanguageWebRequest.Method = "POST";

        // create and send body of request
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string jsonText = serializer.Serialize(text);

        string body = "{ \"documents\": [ { \"id\": \"0\", \"text\": " + jsonText + "} ] }";
        byte[] data = Encoding.UTF8.GetBytes(body);
        detectLanguageWebRequest.ContentLength = data.Length;

        using (var requestStream = detectLanguageWebRequest.GetRequestStream())
            requestStream.Write(data, 0, data.Length);

        HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

        // read and parse JSON response
        var responseStream = response.GetResponseStream();
        var jsonString = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
        dynamic jsonResponse = serializer.DeserializeObject(jsonString);

        // fish out the detected language code
        var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
        if (languageInfo["score"] > (decimal)0.5)
            return languageInfo["iso6391Name"];
        else
            return "";
    }

0 个答案:

没有答案