您的足迹:首页 > 未分类 >用C#写一个AI智能回答机器人

用C#写一个AI智能回答机器人

本文采用的API接口来自于图灵机器人www.tuling123.com 
using System;

using System.IO;

using System.Net;

using System.Web.Script.Serialization;

 

public partial class api_test_api : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

 

    protected void btnSearch_Click(object sender, EventArgs e)

    {

        string key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";//对应自己的图灵机器人的KEY

        string url = "http://www.tuling123.com/openapi/api?key=" + key + "&info=";

        string values = string.Empty;

        if (!String.IsNullOrEmpty(tbInfo.Text.Trim()))

        {

            url += tbInfo.Text.Trim();

            values = GetApiValues(url);

            lblText.Text += "["+DateTime.Now.ToString("HH:mm:ss")+"]"+"你说:" + tbInfo.Text.Trim() + "<br/>"+ "["+DateTime.Now.ToString("HH:mm:ss")+"]"+"机器人说:" + GetWords(values).text + "<br/>";

        }

        tbInfo.Text = "";

    }

 

    /// <summary>

    /// 解析json返回字符串

    /// </summary>

    /// <param name="text">需要解析的文字</param>

    /// <returns></returns>

    public RobotWords GetWords(string text)

    {

        try

        {

            JavaScriptSerializer json = new JavaScriptSerializer(); //实例化一个能够序列化数据的类

            RobotWords list = json.Deserialize<RobotWords>(text); //将json数据转化为对象类型并赋值给list

            return list;

        }

        catch (Exception ex)

        {

            return null;

        }

    }

 

    /// <summary>

    /// 调用API方法

    /// </summary>

    /// <param name="apiUrl"></param>

    /// <returns></returns>

    public string GetApiValues(string apiUrl)

    {

        string receiveData = string.Empty;

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);

        myHttpWebRequest.Timeout = 100000;

        myHttpWebRequest.Method = "GET";

        myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";

 

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

 

        if (myHttpWebResponse.StatusCode.Equals(HttpStatusCode.OK))

        {

            Stream receiveStream = myHttpWebResponse.GetResponseStream();

            StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);

            receiveData = readStream.ReadToEnd();

            receiveStream.Close();

            readStream.Close();

        }

        myHttpWebResponse.Close();

        return receiveData;

    }

 

    /// <summary>

    /// JOSN对应的实体

    /// </summary>

    public class RobotWords

    {

        public string code { get; set; }

 

        public string text { get; set; }

    }

}
本博客所有文章如无特别注明均为原创。作者:cc复制或转载请以超链接形式注明转自 我的博客
原文地址《用C#写一个AI智能回答机器人

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(2)