最近想做一个聊天系统,先说一下怎么实现
为了实现聊天功能,需要图灵api接口,为了连接图灵api需要html post通信传递json字符串数据,json有需要使用c#解析
基本流程:通过 htmlpost 发送json语句,等待web响应获得答复的json,解析json并将结果输出,随后将对话信息保存到数据库中
一、图灵api接口的连接
补充知识 post数据 提交与接收
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create("http://openapi.tuling123.com/openapi/api/v2");
webrequest.Method = "post";
string post = str;
byte[] postdatabyte = Encoding.UTF8.GetBytes(post);
webrequest.ContentLength = postdatabyte.Length;
Stream stream;
stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
using (var httpWebResponse = webrequest.GetResponse())
{
using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
{
string ret = responseStream.ReadToEnd();
Console.WriteLine(ret);
}
}
二、json数据的解析
为了完成json数据的处理,需要进行解析。首先我们需要添加程序包Newtonsoft,程序管理器控制台中输入命令:Install-Package Newtonsoft.Json即可。然后引用:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
这样开发前的基础工作就做好了。