Client3.cs ``` using System; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; /// 请求体签名客户端。 public sealed class Client3 { /// 服务器源。 /// http://api.group.mes/open/ public string Source { get; private set; } /// 令牌。 public string Token { get; private set; } /// 密钥。 public string Secret { get; private set; } /// 构造函数,创建客户端实例。 public Client3(string source, string token, string secret) { if (string.IsNullOrEmpty(source)) throw new ArgumentException("未指定服务器源。"); if (string.IsNullOrEmpty(token)) throw new ArgumentException("未指定令牌。"); if (string.IsNullOrEmpty(secret)) throw new ArgumentException("未指定密钥。"); Source = source; Token = token; Secret = secret; } /// 发送 POST 请求。 /// 要调用的方法。 /// 请求体 JSON 字符串。 /// HTTP 响应体 /// /// public string Post(string func, string json) { // 请求体 var body = Encoding.UTF8.GetBytes(json ?? ""); // 计算签名 var stamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds).ToString(); var sha256 = Sha256(body); var sample = Secret + "\n" + stamp + "\n" + sha256; var signature = Sha256(Encoding.UTF8.GetBytes(sample)); // 发起 HTTP 请求 var url = Source + func; var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = body.Length; request.Headers.Add("Token", Token); request.Headers.Add("Stamp", stamp); request.Headers.Add("Signature", signature); request.GetRequestStream().Write(body, 0, body.Length); var response = request.GetResponse() as HttpWebResponse; using (var memory = new MemoryStream()) { var stream = response.GetResponseStream(); var buffer = new byte[4096]; while (true) { var count = stream.Read(buffer, 0, buffer.Length); if (count < 1) break; memory.Write(buffer, 0, count); } return Encoding.UTF8.GetString(memory.ToArray()); } } /// 计算 SHA256,获取哈希的小写十六进制。 /// static string Sha256(byte[] bytes) { using (var provider = new SHA256CryptoServiceProvider()) { var hash = provider.ComputeHash(bytes); provider.Clear(); const string hex = "0123456789abcdef"; var chars = new char[hash.Length * 2]; for (var i = 0; i < hash.Length; i++) { var b = hash[i]; var offset = i * 2; chars[offset] = hex[b / 16]; chars[offset + 1] = hex[b % 16]; } return new string(chars); } } } ``` Program.cs ``` using System; class Program { static void Main(string[] args) { // 准备客户端 var client3 = new Client3("http://127.0.0.1:8033/open/", "token3", "secret3"); // 发起接口请求 var response = client3.Post("checked", ""); Console.WriteLine(response); } } ```