最近研究微信公众平台,搭建了一个微信聊天机器人,调用小黄鸡的公众接口,实现在线和小黄鸡聊天的功能。

接口调用不是很麻烦,不过是php版本,所以研究了一下C#的功能模块,

Winfrom版

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.Threading; namespace 小贱鸡
{
public partial class Form1 : Form
{
private static string cookie = null;
private string msg = "";
private Thread th2 = null;
private Thread th3 = null;
private bool changed = false; public Form1()
{
InitializeComponent();
simsimi.SetAllowUnsafeHeaderParsing20();
Thread th = new Thread(new ThreadStart(Cookie_Thread));
th2 = new Thread(new ThreadStart(Hi_Thread));
th3 = new Thread(new ThreadStart(PowerOn_Thread));
th.Start();
th2.Start();
th3.Start();
} private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
changed = true;
msg = textBox1.Text;
textBox1.Text = "";
richTextBox1.Text += String.Format("Me:{0}\n", msg);
changed = false;
}
} private static void Cookie_Thread()
{
cookie = simsimi.GetCookie();
}
private void PowerOn_Thread()
{
while (cookie == null)
{
this.Invoke(new Action(Update_PowerText), null);
Thread.Sleep(1500);
}
this.Invoke(new Action(Update_PowerFinalText), null);
}
private void Update_PowerText()
{
richTextBox1.Text += "正在开鸡中。。。\n";
}
private void Update_PowerFinalText()
{
richTextBox1.Text += "唔,终于开鸡了。\n小贱鸡:你好,我是小贱鸡。o(∩_∩)o\n";
}
private void Hi_Thread()
{
while (true)
{
while (changed)
{
this.Invoke(new Action(Update_Text), null);
break;
}
}
}
private void Update_Text()
{
richTextBox1.Text += String.Format("小贱鸡:{0}\n", simsimi.Hi_Simsimi(msg,cookie));
} private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13)
{
if (textBox1.Text != "")
{
changed = true;
msg = textBox1.Text;
textBox1.Text = "";
richTextBox1.Text += String.Format("Me:{0}\n", msg);
changed = false;
}
}
} private void richTextBox1_TextChanged(object sender, EventArgs e)
{
//设定光标所在位置
this.richTextBox1.SelectionStart = richTextBox1.TextLength-1;
//滚动到当前光标处
this.richTextBox1.ScrollToCaret();
} }
}

Code

应用的类代码:应用接口用小黄鸡那边传回来的是一个json形式的内容,所以应用到json的解析问题,我应用的是网上通用的方法Newtonsoft.Json,可以从网上下载对应的DLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; namespace 小贱鸡
{
class simsimi
{
/// <summary>
/// Cookie
/// </summary>
/// <returns></returns>
public static string GetCookie()
{
string Cookiesstr = null;
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create("http://www.simsimi.com/talk.htm");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//Get the response from the server and save the cookies from the request..
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri); return Cookiesstr;
} public static string Hi_Simsimi(string que, string cookies)
{
string ans = "我们换个话题吧";
string url = String.Format("http://www.simsimi.com/func/reqN?lc=ch&ft=0.0&req={0}&fl=http%3A%2F%2Fwww.simsimi.com%2Ftalk.htm", que);
HttpWebRequest hi_request = null;
try
{
hi_request = (HttpWebRequest)WebRequest.Create(url);
hi_request.Method = "GET";
hi_request.KeepAlive = true;
hi_request.ServicePoint.Expect100Continue = false; hi_request.AllowWriteStreamBuffering = false;
//终端信息
hi_request.Accept = "application/json,text/javascript,*/*;q=0.01";
hi_request.Headers.Add("Accept-Language", "zh-cn");
hi_request.Headers.Add("Accept-Encoding", "gzip,deflate");
hi_request.Headers.Add("Cookie", cookies + ";simsimi_uid=1;");
hi_request.Referer = "http://www.simsimi.com/talk.htm";
hi_request.UserAgent = "Mozilla/4.0(compatible;MSIE 7.0;Windows NT 6.1;Trident/5.0;SLCC2;.NET CLR 2.0.50727;.NET CLR 3.5.30729;.NET CLR 3.0.30729;.NET4.0C;.NET4.0E)";
hi_request.ContentType = "application/json;charset=utf-8"; hi_request.AllowAutoRedirect = false;
HttpWebResponse hi_response = (HttpWebResponse)hi_request.GetResponse();
StreamReader sr = new StreamReader(hi_response.GetResponseStream(), Encoding.UTF8);
ans = sr.ReadToEnd();
if (ans != "{}")
{ JObject jo = JObject.Parse(ans);
string[] ArrayList = jo.Properties().Select(item => item.Value.ToString()).ToArray();
if (ArrayList[0] == "200")
{
ans = ArrayList[6];
}
else
{
ans = "没有听懂,可以再说一遍吗?";
}
}
hi_request.Abort();
hi_response.Close();
}
catch (System.Exception e)
{ Console.WriteLine(e.ToString());
//return e.ToString();
return "不好意思死鸡了⊙︿⊙重启下程序吧~";
} return ans;
} public static bool SetAllowUnsafeHeaderParsing20()
{
//Get the assembly that contains the internal class
Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
if (aNetAssembly != null)
{
//Use the assembly in order to get the internal type for the internal class
Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (aSettingsType != null)
{
//Use the internal static property to get an instance of the internal settings class.
//If the static instance isn't created allready the property will create it for us.
object anInstance = aSettingsType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { }); if (anInstance != null)
{
//Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null)
{
aUseUnsafeHeaderParsing.SetValue(anInstance, true);
return true;
}
}
}
}
return false;
}
}
}

Code

最新文章

  1. 1009: [HNOI2008]GT考试
  2. 【Linux驱动】内核等待队列
  3. HTML基础(二)——表单,图片热点,网页划区和拼接
  4. [UWP]一种利用Behavior 将StateTrigger集中管理的方案
  5. ASP.NET内置对象之Request传递请求对象
  6. (转)如何正确使用C++多重继承
  7. POJ 2531 Network Saboteur 位运算子集枚举
  8. 定时任务备份数据库与windows批处理
  9. 【vue系列之二】详解vue-cli 2.0配置文件
  10. junit源码解析--捕获测试结果
  11. 详解BLE 空中包格式—兼BLE Link layer协议解析
  12. Gradle 1.12用户指南翻译——第四十九章. Build Dashboard 插件
  13. project 2013 工时完成百分比不会自动更新填充
  14. codeforces #305 E Mike and friends
  15. vue中使用echarts来绘制世界地图和中国地图
  16. 应用程序挂起、复原与终止— IOS开发
  17. linux fack 文件系统修复命令
  18. linux 配置svn服务器+使用+注意事项
  19. centos7 安装git
  20. 旋转 3d

热门文章

  1. JBoss 7 更改response header中的Server参数
  2. QtDesigner与程序设计模式
  3. InfoPath读取List到重复表
  4. Linux内存寻址之分段机制及分页机制【转】
  5. ConcurrentModificationException探究
  6. TruncateATable 清除一张表
  7. vc MFC 通过IDispatch调用默认成员函数
  8. 团队作业7——第二次项目冲刺(Beta版本)day1
  9. Spring线程池配置模板设计(基于Springboot)
  10. 类与对象 - Java学习(二)