• C# 调用网易“易盾” Web API


    易盾是网易推出的反垃圾云服务,最近准备试用一下,但发现api文档中只提供了Java, Python, PHP的示例代码,却没有C#的示例代码,于是参照Java示例代码用C#实现了一下。

    Java中用HashMap构建公共参数与私有参数,C#中则可以用Dictionary:

    var parameters = new Dictionary<string, string>();
    //公共参数
    parameters.Add("secretId", "{secretId}");
    parameters.Add("businessId", "{businessId}");
    parameters.Add("version", "v2");
    parameters.Add("timestamp", CurrentTimeMillis().ToString());
    parameters.Add("nonce", new Random().Next().ToString());
    //私有参数
    parameters.Add("dataId", Guid.NewGuid().ToString());
    parameters.Add("content", content);
    parameters.Add("dataOpType", "1");
    parameters.Add("ip", ip); 

    Java中用 System.currentTimeMillis() 生成 timestamp,C#中没有直接的对应实现,只能另外实现一个(来自C# 实现 Java 的 System.currentTimeMillis() 值):

    private long CurrentTimeMillis()
    {
        return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    }

    对于生成签名的操作,Java中稍显复杂,C#中用Lambda一气呵成:

    private string GenerateSignature(Dictionary<string, string> parameters, string secretKey)
    {
        var signatueString = string.Join(string.Empty,
            parameters.OrderBy(p => p.Key).Select(p => p.Key + p.Value))
            + secretKey;
    
        return string.Join(string.Empty,
            MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(signatueString)).Select(s => s.ToString("x2")));
    }

    对于http请求操作,Java中有HttpClient,C#中也有:

    var response = await _httpClient.PostAsync("/v2/text/check", 
        new FormUrlEncodedContent(parameters));

    对于响应结果解析,Java中有JsonParser,C#中有Json.NET:

    var responseText = await response.Content.ReadAsStringAsync();
    var jObject = JObject.Parse(responseText);
    var statusCode = jObject["code"].Value<int>();
    if (statusCode == 200)
    {
        var action = jObject["result"]["action"].Value<int>();
        return action == 1;
    }
    else
    {
        return false;
    }

    完整实现代码如下:

    public class YiDunCheckSpam : ICheckSpam
    {
        private const string BASE_ADDRESS = "https://api.aq.163.com/";
        private readonly HttpClient _httpClient;
    
        public YiDunCheckSpam()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(BASE_ADDRESS);
        }
    
        public async Task<bool> IsSpamPost(string title, string content, string author, string ip)
        {
            var parameters = new Dictionary<string, string>();
            //公共参数
            parameters.Add("secretId", "{secretId}");
            parameters.Add("businessId", "{businessId}");
            parameters.Add("version", "v2");
            parameters.Add("timestamp", CurrentTimeMillis().ToString());
            parameters.Add("nonce", new Random().Next().ToString());
            //私有参数
            parameters.Add("dataId", Guid.NewGuid().ToString());
            parameters.Add("content", content);
            parameters.Add("dataOpType", "1");
            parameters.Add("ip", ip);
            parameters.Add("title", title);
            parameters.Add("nickname", author);
    
            var secretKey = "{secretKey}";
            var signature = GenerateSignature(parameters, secretKey);
            parameters.Add("signature", signature);
    
            var response = await _httpClient.PostAsync("/v2/text/check",
                new FormUrlEncodedContent(parameters));
    
            var responseText = await response.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseText);
            var statusCode = jObject["code"].Value<int>();
            if (statusCode == 200)
            {
                var action = jObject["result"]["action"].Value<int>();
                return action > 1;
            }
            else
            {
                return false;
            }
        }
    
        private string GenerateSignature(Dictionary<string, string> parameters, string secretKey)
        {
            var signatueString = string.Join(string.Empty,
                parameters.OrderBy(p => p.Key).Select(p => p.Key + p.Value))
                + secretKey;
    
            return string.Join(string.Empty,
                MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(signatueString)).Select(s => s.ToString("x2")));
        }
    
        private long CurrentTimeMillis()
        {
            return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }
    }
  • 相关阅读:
    初始化mysql数据库 /usr/bin/mysql_install_db执行时报错
    CentOS7安装mysql兼容性问题
    CentOS7网络连接问题以及重启网络服务失败
    CentOS7安装nginx
    zookeeper启动时报错:Error contacting service. It is probably not running问题
    CentOS查看卸载openjdk
    使用yum命令时提示:Another app is currently holding the yum lock
    修改eclipse中文件打开默认方式
    [程序员代码面试指南]链表问题-单链表的选择排序(选择排序)
    [程序员代码面试指南]链表问题-删除无序链表中重复出现的节点
  • 原文地址:https://www.cnblogs.com/dudu/p/5419385.html
Copyright © 2020-2023  润新知