代碼筆記 | 圖靈聊天機器人API調用

 
HttpWebResponse Response = null;
public string ConnectTuLing(string p_strMessage)
{
    string result = null;
    try
    {
        //註冊碼
        String APIKEY = "apikey";
        String _strMessage = p_strMessage;
        String INFO = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(_strMessage));
        String getURL = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
        HttpWebRequest MyRequest = (HttpWebRequest)HttpWebRequest.Create(getURL);
        HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
        Response = MyResponse;
        using (Stream MyStream = MyResponse.GetResponseStream())
        {
            long ProgMaximum = MyResponse.ContentLength;
            long totalDownloadedByte = 0;
            byte[] by = new byte[1024];
            int osize = MyStream.Read(by, 0, by.Length);
            Encoding encoding = Encoding.UTF8;
            while (osize > 0)
            {
                totalDownloadedByte = osize + totalDownloadedByte;
                result += encoding.GetString(by, 0, osize);
                long ProgValue = totalDownloadedByte;
                osize = MyStream.Read(by, 0, by.Length);
            }
        }
        //解析json
        JsonReader reader = new JsonTextReader(new StringReader(result));
        while (reader.Read())
        {
            //獲取text中的內容
            if (reader.Path == "text")
            {
                //結果賦值
                result = reader.Value.ToString();
            }
            Console.WriteLine(reader.TokenType + "\\t\\t" + reader.ValueType + "\\t\\t" + reader.Value);
        }
    }
    catch (Exception)
    {
        throw;
    }
    return result;
}

發佈了3 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章