标签:
这是一个聊天机器人,很方便,直接调用图灵机器人api即可,对话方式一问一答!
图灵机器人官网上只有php和java的示例,于是自己写了个Windows的。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;//程序需引用Newtonsoft.Json 下载地址http://json.codeplex.com/
namespace TuLing
{
public partial class MainForm : Form
{
HttpWebResponse Response = null;
public MainForm()
{
InitializeComponent();
}
//
/// <summary>
/// 对话图灵机器人
/// </summary>
/// <param name="p_strMessage"></param>
/// <returns></returns>
public string ConnectTuLing(string p_strMessage)
{
string result = null;
try
{
//注册码自己到网上注册去
String APIKEY = "c32ccaa805b6441be76bc18074f12e51";
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;
}
private void btn_send_Click(object sender, EventArgs e)
{
string returnMess = ConnectTuLing(rtb_send.Text);
rtb_mess.Text = returnMess;
}
private void btn_close_Click(object sender, EventArgs e)
{
this.this.FindForm().Close();
}
/// <summary>
/// 回车快捷键
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void rtb_send_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
rtb_mess.Text= ConnectTuLing(rtb_send.Text);
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/uoou/p/4538916.html