DingTalk机器人C#代码

时间:2022-02-24 07:34:51

前面已经介绍了机器人的事情,今天直接贴一下代码。

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.IO; using System.IO.Compression; using System.Text.RegularExpressions; namespace 机器人 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string paraUrlCoded = "{\"msgtype\":\"text\",\"text\":{\"content\":\""; paraUrlCoded += textBox2.Text; paraUrlCoded += "\"}}"; Post(paraUrlCoded); } private void button2_Click(object sender, EventArgs e) { string paraUrlCoded = "{\"msgtype\": \"link\", \"link\": {\"text\": \"我的博客:欢迎光临\", \"title\": \"推广博客啦,机器人开发者\", \"picUrl\": \"\", \"messageUrl\": \"http://www.cnblogs.com/left69/\"}}"; Post(paraUrlCoded); } private void Post(string paraUrlCoded) { string url = textBox1.Text; string strURL = url; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.Method = "POST"; //判断是否必要性 request.ContentType = "application/json;charset=UTF-8"; //request.ContentType = "application/json;"; //添加cookie测试 //Uri uri = new Uri(url); //Cookie cookie = new Cookie("Name", DateTime.Now.ToString()); // 设置key、value形式的Cookie //CookieContainer cookies = new CookieContainer(); //cookies.Add(uri, cookie); //request.CookieContainer = cookies; //发送请求的另外形式 //request.Method = "POST"; //request.ContentType = "application/x-www-form-urlencoded"; byte[] payload; payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); request.ContentLength = payload.Length; Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); System.Net.HttpWebResponse response; response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream s; s = response.GetResponseStream(); string StrDate = ""; string strValue = ""; StreamReader Reader = new StreamReader(s, Encoding.UTF8); while ((StrDate = Reader.ReadLine()) != null) { strValue += StrDate + "\r\n"; } //添加关闭相应 Reader.Close(); response.Close(); //改变返回结果形式以看全部提示 label3.Text = strValue; // MessageBox.Show(strValue); } } }

  

程序源码的位置在这儿。%E6%9C%BA%E5%99%A8%E4%BA%BA.7z

参考过的代码有:

发送HTTP请求 - a-dou - 博客园

C# 发送Http协议 模拟 Post Get请求 - kaikaichao - 博客园

钉钉 机器人接入 自定义webhook - 蓝辰进击者 - 博客园