C# + 图灵机器人
程序员文章站
2022-05-29 21:03:18
...
VS + .NET3.5
新建winform窗体应用程序,项目名称为TuringRobotDemo。
从工具箱拖放listBox,button,textBox各一个。需要using Newtonsoft.Json; 文件下载。
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace TuringRobotDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public string ConnectTuLing(string p_strMessage)
{
string result = null;
HttpWebResponse Response = null;
try
{
String APIKEY = "088feb10e3b9dea8d429850f2cd1631c"; //这里是注册时得到的key
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);
}
}
JsonReader reader = new JsonTextReader(new StringReader(result));
while (reader.Read())
{
if (reader.Path == "text")
{
result = reader.Value.ToString();
}
}
}
catch (Exception)
{
throw;
}
return result;
}
private void button1_Click(object sender, EventArgs e)
{
string sendText = textBox1.Text;
listBox1.Items.Add("我:"+ sendText);
string returnText = ConnectTuLing(sendText);
listBox1.Items.Add("机器人:" + returnText);
textBox1.Text = "";
}
}
}
截图如下: