本文的目標是:用“簽名方法 v3”調用“錄音文件識別請求”接口
v3文檔中提供了各大編程語言的演示代碼,選擇合適自己的。
其它接口的文檔寫得挺好懂的,示例代碼復制過來就能用,
就這個v3的文檔,我感覺寫不太明白,首次接觸真的很懵逼!
現在自己調用成功了特此來記錄下。
一、修改公共參數:
v3中有這么幾個參數:
對應以下畫圈圈的做修改:
所以得到修改后的代碼:
string service = "asr"; string endpoint = "asr.tencentcloudapi.com"; string region = ""; string action = "CreateRecTask"; string version = "2019-06-14";
二、修改提交參數
v3中有這么一個變量(就是你要提交的參數的json格式):
string requestPayload = "{\"Limit\": 1, \"Filters\": [{\"Values\": [\"\\u672a\\u547d\\u540d\"], \"Name\": \"instance-name\"}]}";
修改為目標接口的參數(按需提供、去掉公共參數):
StringBuilder parameter = new StringBuilder(); parameter.Append("{"); parameter.Append("\"EngineModelType\":\"16k_zh\","); parameter.Append("\"ChannelNum\":1,"); parameter.Append("\"SourceType\":1,"); parameter.Append("\"Data\":\"base64\","); parameter.Append("\"ResTextFormat\":1,"); parameter.Append("\"FilterPunc\":2"); parameter.Append("}"); string requestPayload = parameter.ToString();
三、發送請求
到這一步就OK了:
var headers = Application.BuildHeaders(SECRET_ID, SECRET_KEY, service , endpoint, region, action, version, DateTime.UtcNow, requestPayload); HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://{endpoint}"); request.Method = "post"; foreach (KeyValuePair<string, string> kv in headers) { request.Headers.Add(kv.Key, kv.Value); } byte[] byteData = Encoding.UTF8.GetBytes(requestPayload); request.ContentLength = byteData.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string result = reader.ReadToEnd(); response.Close(); reader.Dispose();
最后貼出完整代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Net; 5 using System.Security.Cryptography; 6 using System.Text; 7 8 namespace ConsoleDemo 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 // 填入你自己的密鑰參數 15 string SECRET_ID = ""; 16 string SECRET_KEY = ""; 17 18 string service = "asr"; 19 string endpoint = "asr.tencentcloudapi.com"; 20 string region = ""; 21 string action = "CreateRecTask"; 22 string version = "2019-06-14"; 23 24 StringBuilder parameter = new StringBuilder(); 25 parameter.Append("{"); 26 parameter.Append("\"EngineModelType\":\"16k_zh\","); 27 parameter.Append("\"ChannelNum\":1,"); 28 parameter.Append("\"SourceType\":1,"); 29 parameter.Append("\"Data\":\"base64\","); 30 parameter.Append("\"ResTextFormat\":1,"); 31 parameter.Append("\"FilterPunc\":2"); 32 parameter.Append("}"); 33 string requestPayload = parameter.ToString(); 34 35 var headers = Application.BuildHeaders(SECRET_ID, SECRET_KEY, service 36 , endpoint, region, action, version, DateTime.UtcNow, requestPayload); 37 38 HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://{endpoint}"); 39 request.Method = "post"; 40 41 foreach (KeyValuePair<string, string> kv in headers) 42 { 43 request.Headers.Add(kv.Key, kv.Value); 44 } 45 46 byte[] byteData = Encoding.UTF8.GetBytes(requestPayload); 47 request.ContentLength = byteData.Length; 48 49 using (Stream postStream = request.GetRequestStream()) 50 { 51 postStream.Write(byteData, 0, byteData.Length); 52 } 53 54 WebResponse response = request.GetResponse(); 55 StreamReader reader = new StreamReader(response.GetResponseStream()); 56 string result = reader.ReadToEnd(); 57 58 response.Close(); 59 reader.Dispose(); 60 } 61 } 62 63 public class Application 64 { 65 public static string SHA256Hex(string s) 66 { 67 using (SHA256 algo = SHA256.Create()) 68 { 69 byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s)); 70 StringBuilder builder = new StringBuilder(); 71 for (int i = 0; i < hashbytes.Length; ++i) 72 { 73 builder.Append(hashbytes[i].ToString("x2")); 74 } 75 return builder.ToString(); 76 } 77 } 78 79 public static byte[] HmacSHA256(byte[] key, byte[] msg) 80 { 81 using (HMACSHA256 mac = new HMACSHA256(key)) 82 { 83 return mac.ComputeHash(msg); 84 } 85 } 86 87 public static Dictionary<String, String> BuildHeaders(string secretid, 88 string secretkey, string service, string endpoint, string region, 89 string action, string version, DateTime date, string requestPayload) 90 { 91 string algorithm = "TC3-HMAC-SHA256"; 92 string datestr = date.ToString("yyyy-MM-dd"); 93 DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); 94 long requestTimestamp = (long)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / 1000; 95 96 // ************* 步驟 1:拼接規范請求串 ************* 97 string httpRequestMethod = "POST"; 98 string canonicalUri = "/"; 99 string canonicalQueryString = ""; 100 string contentType = "application/json"; 101 string canonicalHeaders = "content-type:" + contentType + "; charset=utf-8\n" + "host:" + endpoint + "\n"; 102 string signedHeaders = "content-type;host"; 103 string hashedRequestPayload = SHA256Hex(requestPayload); 104 string canonicalRequest = httpRequestMethod + "\n" 105 + canonicalUri + "\n" 106 + canonicalQueryString + "\n" 107 + canonicalHeaders + "\n" 108 + signedHeaders + "\n" 109 + hashedRequestPayload; 110 Console.WriteLine(canonicalRequest); 111 Console.WriteLine("----------------------------------"); 112 113 // ************* 步驟 2:拼接待簽名字符串 ************* 114 string credentialScope = datestr + "/" + service + "/" + "tc3_request"; 115 string hashedCanonicalRequest = SHA256Hex(canonicalRequest); 116 string stringToSign = algorithm + "\n" + requestTimestamp.ToString() + "\n" + credentialScope + "\n" + hashedCanonicalRequest; 117 Console.WriteLine(stringToSign); 118 Console.WriteLine("----------------------------------"); 119 120 // ************* 步驟 3:計算簽名 ************* 121 byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretkey); 122 byte[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr)); 123 byte[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service)); 124 byte[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request")); 125 byte[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign)); 126 string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower(); 127 Console.WriteLine(signature); 128 Console.WriteLine("----------------------------------"); 129 130 // ************* 步驟 4:拼接 Authorization ************* 131 string authorization = algorithm + " " 132 + "Credential=" + secretid + "/" + credentialScope + ", " 133 + "SignedHeaders=" + signedHeaders + ", " 134 + "Signature=" + signature; 135 Console.WriteLine(authorization); 136 Console.WriteLine("----------------------------------"); 137 138 Dictionary<string, string> headers = new Dictionary<string, string>(); 139 headers.Add("Authorization", authorization); 140 headers.Add("Host", endpoint); 141 headers.Add("Content-Type", contentType + "; charset=utf-8"); 142 headers.Add("X-TC-Timestamp", requestTimestamp.ToString()); 143 headers.Add("X-TC-Version", version); 144 headers.Add("X-TC-Action", action); 145 headers.Add("X-TC-Region", region); 146 return headers; 147 } 148 } 149 }