• 阿里云消息队列的C#使用http接口发送消息实例


    app.config

      <appSettings>
        <clear/>
        <add key="Ons_Topic" value="XXX_FinishOrder"/>
        <add key="Ons_AccessKey" value="jmXXXXXBov"/>
        <add key="Ons_SecretKey" value="VXXXXXjRD7pxYCpjtnJDDbsH"/>
        <add key="Ons_ConsumerId" value="CID_xxxxxxxx"/>
        <add key="Ons_ProducerID" value="PID_xxxxxxxxxxx"/>
      </appSettings>

    program.cs

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using ons;
    using test;
    using System.Security.Cryptography;
    
    namespace MqSDk
    {
        class Program
        {
            /// <summary>
            /// method to generate a MD5 hash of a string
            /// </summary>
            /// <param name="strToHash">string to hash</param>
            /// <returns>hashed string</returns>
            public static string GenerateMd5(string strToHash)
            {
                var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] emailBytes = Encoding.UTF8.GetBytes(strToHash.ToLower());
                byte[] hashedEmailBytes = md5.ComputeHash(emailBytes);
                StringBuilder sb = new StringBuilder();
                foreach (var b in hashedEmailBytes)
                {
                    sb.Append(b.ToString("x2").ToLower());
                }
                return sb.ToString();
            }
    
            static void Main(string[] args)
            {
                            //# 公测url
                            string url = "http://publictest-rest.ons.aliyun.com/";
                            HttpClient client = new HttpClient();
                            string onsTopic = ConfigurationManager.AppSettings["Ons_Topic"];
                            string onsProducerId = ConfigurationManager.AppSettings["Ons_ProducerID"];
                            string onsAccessKey = ConfigurationManager.AppSettings["Ons_AccessKey"];
                            string onsSecretKey = ConfigurationManager.AppSettings["Ons_SecretKey"];
                            string onsConsumerId = ConfigurationManager.AppSettings["Ons_ConsumerId"];
                            String body = @"{""value"": ""test""}";
                            var newline = "
    ";
                            for (int i = 0; i < 10; i++)
                            {
                                //var date = DateTime.Now.TimeOfDay.TotalMilliseconds.ToString("F0");
                                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                                var date = Convert.ToInt64(ts.TotalMilliseconds).ToString();
                                HttpContent content = new StringContent(body);
                                var md5Str = GenerateMd5(body);
                                //db2421caefd6e8163e1928da4f53cc67
                                var signString = onsTopic + newline + onsProducerId + newline + md5Str + newline + date;
                                String sign = EncryptToSha1(signString, onsSecretKey);
                                Console.WriteLine(sign);
                                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                                content.Headers.Add("Signature", sign);
                                content.Headers.Add("AccessKey", onsAccessKey);
                                content.Headers.Add("ProducerID", onsProducerId);
                                var rurl = url + "message/?topic=" + onsTopic + "&time=" + date + "&tag=http" + "&key=http";
                                Console.WriteLine(rurl);
                                client.PostAsync(rurl, content).ContinueWith(
                                    requestTask =>
                                    {
                                        // Get HTTP response from completed task. 
                                        HttpResponseMessage response = requestTask.Result;
    
                                        // Check that response was successful or throw exception 
                                        response.EnsureSuccessStatusCode();
    
                                        // Read response asynchronously as JsonValue and write out top facts for each country 
                                        response.Content.ReadAsStringAsync().ContinueWith(
                                            (readTask) =>
                                            {
                                                Console.WriteLine(readTask.Result);
                                            });
                                    }
                                    );
                            }
                            Console.ReadLine();
            }
    
            #region 获取由SHA1加密的字符串
    
            /// <summary>
            /// sha1 加密,与php加密结果一样
            /// </summary>
            /// <param name="str"></param>
            /// <param name="keys"></param>
            /// <returns></returns>
            public static string EncryptToSha1(string str, string keys)
            {
                return hash_hmac(str, keys, true);
            }
            private static string hash_hmac(string signatureString, string secretKey, bool raw_output = false)
            {
                var enc = Encoding.UTF8;
                HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
                hmac.Initialize();
    
                byte[] buffer = enc.GetBytes(signatureString);
                if (raw_output)
                {
                    return Convert.ToBase64String(hmac.ComputeHash(buffer));
                }
                else
                {
                    return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
                }
            }
            #endregion
    
        }
    }
  • 相关阅读:
    Spring AOP 代理创建方式
    VS全局搜索
    uni-app中添加AES加密
    中国菜刀"连接被重置"问题解决
    Windows go get下载包失败问题解决
    搭建vulhub 漏洞环境及安装Docker和docker-compose
    DedeCMS 5.7通用重装漏洞分析
    各就各位,预备,GO!
    ARL资产灯塔系统分组资产导出脚本
    玩《巫师3》需要了解的背景知识
  • 原文地址:https://www.cnblogs.com/xyfy/p/aliyunmq.html
Copyright © 2020-2023  润新知