obsidian/笔记文件/2.笔记/charp发送post请求_飞书机器人举例.md
2025-03-26 00:02:56 +08:00

2.4 KiB
Raw Permalink Blame History

#unity/日常积累

新建一个HttpHelper的类其中的静态方法分别是post和get一个json数据体

using System;
using System.Data;
using System.Globalization;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net;

public class HttpHelper
{
    public static JObject PostJson(string url, Dictionary<string, object> param)
    {
        string paramStr = JsonConvert.SerializeObject(param);
        byte[] data = Encoding.UTF8.GetBytes(paramStr);
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json";

        Stream newStream = request.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();

        request.ServicePoint.Expect100Continue = false;
        request.ProtocolVersion = HttpVersion.Version11;

        var response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            return JObject.Parse(responseString);
        }

        return null;
    }
    public static JObject GetJson(string url)
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        var response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            return JObject.Parse(responseString);
        }
        return null;
    }
}

飞书机器人对应的Hook是这个

!Pasted image 20240911193115.png

如果需要调用的话组装一个dictionary结构体传参过去即可

        Dictionary<string, object> dict = new Dictionary<string, object>();
        Dictionary<string,string> content = new Dictionary<string, string>();
        content.Add("text",$"热更包");
        dict.Add("msg_type", "text");
        dict.Add("content", content);
        // dict.Add("name", "张三");

        string url = "https://open.larksuite.com/open-apis/bot/v2/hook/38ebaa0a-ed93-48b1-a6ac-c9cd5d20942a";
        string json = HttpHelper.PostJson(url, dict).ToString();