1 //获取时间戳 .net framework 2 /* 3 DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 4 int time = (int)(DateTime.Now - dt).TotalSeconds; 5 String Timestamp = time.ToString(); 6 */ 7 // .net core 获取时间戳 8 DateTime dt = new DateTime(1970, 1, 1,0, 0, 0, DateTimeKind.Utc); 9 int time = (int)(DateTime.Now.AddHours(-8) - dt).TotalSeconds; 10 String Timestamp = time.ToString(); 11 //随机正整数,用于防止重放攻击 12 Random rd = new Random(); 13 int rd_i = rd.Next(); 14 String nonce = Convert.ToString(rd_i); 15 //SecretId 16 String SecretId = ""; 17 //参数(用于编码) 18 String PostStr = string.Format("Action=DescribeLVBChannelList&Nonce={0}&Region=bj&SecretId={1}&Timestamp={2}", nonce, SecretId, Timestamp); 19 //地址 20 String url = "https://live.api.qcloud.com/v2/index.php"; 21 //编码 22 UTF8Encoding enc = new UTF8Encoding(); 23 String qm = "POSTlive.api.qcloud.com/v2/index.php" + "?" + PostStr; 24 byte[] dataToHash = enc.GetBytes(qm); 25 /* 26 var sha1 = SHA1.Create(); 27 var result = sha1.ComputeHash(dataToHash); 28 */ 29 HMACSHA1 hmac = new HMACSHA1() 30 { 31 Key = enc.GetBytes("")//SecretKey 32 }; 33 var result = hmac.ComputeHash(dataToHash); 34 string Signature = Convert.ToBase64String(result); 35 //完整参数 36 var completeUrl = string.Format("Action=DescribeLVBChannelList&Nonce={0}&Region=bj&SecretId={1}&Signature={2}&Timestamp={3}", nonce, SecretId, Signature, Timestamp); 37 38 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 39 request.Method = "POST"; 40 request.ContentType = "application/x-www-form-urlencoded"; 41 request.ProtocolVersion = HttpVersion.Version10; 42 byte[] data = Encoding.UTF8.GetBytes(completeUrl); 43 request.ContentLength = data.Length; 44 Stream newStream = request.GetRequestStream(); 45 newStream.Write(data, 0, data.Length); 46 newStream.Close(); 47 HttpWebResponse response = null; 48 int httpStatus = 200; 49 string content; 50 try 51 { 52 response = (HttpWebResponse)request.GetResponse(); 53 httpStatus = (int)response.StatusCode; 54 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 55 content = reader.ReadToEnd(); 56 } 57 catch (WebException e) 58 { 59 response = (HttpWebResponse)e.Response; 60 httpStatus = (int)response.StatusCode; 61 using (Stream errData = response.GetResponseStream()) 62 { 63 using (StreamReader reader = new StreamReader(errData)) 64 { 65 content = reader.ReadToEnd(); 66 } 67 } 68 }