c#调用腾讯云API的实例

时间:2023-06-09 11:20:44
       //获取时间戳 .net framework
/*
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
int time = (int)(DateTime.Now - dt).TotalSeconds;
String Timestamp = time.ToString();
*/
// .net core 获取时间戳
DateTime dt = new DateTime(, , ,, , , DateTimeKind.Utc);
int time = (int)(DateTime.Now.AddHours(-) - dt).TotalSeconds;
String Timestamp = time.ToString();
//随机正整数,用于防止重放攻击
Random rd = new Random();
int rd_i = rd.Next();
String nonce = Convert.ToString(rd_i);
//SecretId
String SecretId = "";
//参数(用于编码)
String PostStr = string.Format("Action=DescribeLVBChannelList&Nonce={0}&Region=bj&SecretId={1}&Timestamp={2}", nonce, SecretId, Timestamp);
//地址
String url = "https://live.api.qcloud.com/v2/index.php";
//编码
UTF8Encoding enc = new UTF8Encoding();
String qm = "POSTlive.api.qcloud.com/v2/index.php" + "?" + PostStr;
byte[] dataToHash = enc.GetBytes(qm);
/*
var sha1 = SHA1.Create();
var result = sha1.ComputeHash(dataToHash);
*/
HMACSHA1 hmac = new HMACSHA1()
{
Key = enc.GetBytes("")//SecretKey
};
var result = hmac.ComputeHash(dataToHash);
string Signature = Convert.ToBase64String(result);
//完整参数
var completeUrl = string.Format("Action=DescribeLVBChannelList&Nonce={0}&Region=bj&SecretId={1}&Signature={2}&Timestamp={3}", nonce, SecretId, Signature, Timestamp); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ProtocolVersion = HttpVersion.Version10;
byte[] data = Encoding.UTF8.GetBytes(completeUrl);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, , data.Length);
newStream.Close();
HttpWebResponse response = null;
int httpStatus = ;
string content;
try
{
response = (HttpWebResponse)request.GetResponse();
httpStatus = (int)response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
content = reader.ReadToEnd();
}
catch (WebException e)
{
response = (HttpWebResponse)e.Response;
httpStatus = (int)response.StatusCode;
using (Stream errData = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(errData))
{
content = reader.ReadToEnd();
}
}
}