坐峰怀雪灬

路漫漫其修远兮,吾将上下而求索。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

百度短信API开发

Posted on 2017-09-05 00:58  坐峰怀雪灬  阅读(653)  评论(0编辑  收藏  举报

由于楼主学的是C#,所以目前做的百度短信API是C#版的,废话不说了,直接上代码。

  1 public void PostData()
  2         {
  3             string url = "http://sms.bj.baidubce.com/bce/v2/message";
  4             //string url = "http://sms.bj.baidubce.com/v1/message";
  5             string ak = "*******";
  6             string sk = "*******";
  7             string jsonStr = "{\"invokeId\":\"调用ID\",\"phoneNumber\":\"18102301717\",\"templateCode\":\"smsTpl:b43d4ccc-7ca6-49dd-90af-faea6b4f2190\",\"contentVar\":{ \"feeType\": \"物业费\",\"fee\":\"80\"}}";
  8             HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
  9             Uri uri = httpRequest.RequestUri;
 10             httpRequest.Method = "POST";
 11             HttpWebResponse httpResponse = null;
 12             DateTime now = DateTime.Now;
 13             int expirationInSeconds = 1800;
 14             string signDate = now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssK");
 15             string authString = "bce-auth-v1/" + ak + "/" + signDate + "/" + expirationInSeconds;
 16             string signingKey = Hex(new HMACSHA256(Encoding.UTF8.GetBytes(sk)).ComputeHash(Encoding.UTF8.GetBytes(authString)));
 17             string canonicalRequestString = CanonicalRequest(httpRequest);
 18             string signature = Hex(new HMACSHA256(Encoding.UTF8.GetBytes(signingKey)).ComputeHash(Encoding.UTF8.GetBytes(canonicalRequestString)));
 19             string authorization = authString + "/host/" + signature;
 20             httpRequest.ContentType = "application/json";
 21             httpRequest.KeepAlive = false;
 22             httpRequest.Headers["Authorization"] = authorization;
 23             httpRequest.Headers["x-bce-content-sha256"] = signingKey;
 24             httpRequest.Headers["x-bce-date"] = signDate;
 25             if (0 < jsonStr.Length)
 26             {
 27                 byte[] data = Encoding.UTF8.GetBytes(jsonStr);
 28                 using (Stream stream = httpRequest.GetRequestStream())
 29                 {
 30                     stream.Write(data, 0, data.Length);
 31                 }
 32             }
 33             try
 34             {
 35                 httpResponse = (HttpWebResponse)httpRequest.GetResponse();
 36             }
 37             catch (WebException ex)
 38             {
 39                 httpResponse = (HttpWebResponse)ex.Response;
 40             }
 41             Console.WriteLine(httpResponse.StatusCode);
 42             Console.WriteLine(httpResponse.Method);
 43             Console.WriteLine(httpResponse.Headers);
 44             Stream st = httpResponse.GetResponseStream();
 45             StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
 46             Console.WriteLine(reader.ReadToEnd());
 47             Console.WriteLine("\n");
 48         }
 49         static string UriEncode(string input, bool encodeSlash = false)
 50         {
 51             StringBuilder builder = new StringBuilder();
 52             foreach (byte b in Encoding.UTF8.GetBytes(input))
 53             {
 54                 if ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' || b == '-' || b == '~' || b == '.')
 55                 {
 56                     builder.Append((char)b);
 57                 }
 58                 else if (b == '/')
 59                 {
 60                     if (encodeSlash)
 61                     {
 62                         builder.Append("%2F");
 63                     }
 64                     else
 65                     {
 66                         builder.Append((char)b);
 67                     }
 68                 }
 69                 else
 70                 {
 71                     builder.Append('%').Append(b.ToString("X2"));
 72                 }
 73             }
 74             return builder.ToString();
 75         }
 76 
 77         static string Hex(byte[] data)
 78         {
 79             var sb = new StringBuilder();
 80             foreach (var b in data)
 81             {
 82                 sb.Append(b.ToString("x2"));
 83             }
 84             return sb.ToString();
 85         }
 86 
 87         static string CanonicalRequest(HttpWebRequest req)
 88         {
 89             Uri uri = req.RequestUri;
 90             StringBuilder canonicalReq = new StringBuilder();
 91             canonicalReq.Append(req.Method).Append("\n").Append(UriEncode(Uri.UnescapeDataString(uri.AbsolutePath))).Append("\n");
 92 
 93             var parameters = HttpUtility.ParseQueryString(uri.Query);
 94             List<string> parameterStrings = new List<string>();
 95             foreach (KeyValuePair<string, string> entry in parameters)
 96             {
 97                 parameterStrings.Add(UriEncode(entry.Key) + '=' + UriEncode(entry.Value));
 98             }
 99             parameterStrings.Sort();
100             canonicalReq.Append(string.Join("&", parameterStrings.ToArray())).Append("\n");
101 
102             string host = uri.Host;
103             if (!(uri.Scheme == "https" && uri.Port == 443) && !(uri.Scheme == "http" && uri.Port == 80))
104             {
105                 host += ":" + uri.Port;
106             }
107             canonicalReq.Append("host:" + UriEncode(host));
108             return canonicalReq.ToString();
109         }