官方文件:https://cloud.tencent.com/document/product/641/12422
請求官方API及簽名的生成程式碼如下:
var urlList = new List<string>(); urlList.Add(url); //請求引數 var req = new { appid = ConfigurationManager.AppSettings["AppId"], url_list = urlList }; var psotJson = JsonConvert.SerializeObject(req); TencentCloundPicHelper tencentHelper = new TencentCloundPicHelper(); var info = tencentHelper.SendPost(psotJson); TencentJianHuangResponse response = JsonConvert.DeserializeObject<TencentJianHuangResponse>(info); if (response != null && response.result_list.Any()) { if (response.result_list.FirstOrDefault().code == 0)//成功 { if (response.result_list.FirstOrDefault().data.result != 0)//是黃圖 { responseMessage.Message = CommonConst.PicNolegal; responseMessage.ResultCode = "555"; responseMessage.Info = new { Url = url, TencentJson = info }; return responseMessage; } } }
public class TencentJianHuangResponse { public List<ImgInfo> result_list = new List<ImgInfo>(); } public class ImgInfo{ /// <summary> /// 錯誤碼,0 為成功 /// </summary> public int code { set; get; } /// <summary> /// 伺服器返回的資訊 /// </summary> public string message { set; get; } /// <summary> /// 當前圖片的 url /// </summary> public string url { set; get; } /// <summary> /// 具體查詢資料,具體見實體 /// </summary> public Data data; } public class Data { /// <summary> /// 0 正常,1 黃圖,2 疑似圖片 /// </summary> public int result { set; get; } /// <summary> /// 封禁狀態,0 表示正常,1 表示圖片已被封禁(只有儲存在騰訊雲的圖片才會被封禁) /// </summary> public int forbid_status { set; get; } /// <summary> /// 識別為黃圖的置信度,分值 0-100;是 normal_score , hot_score , porn_score的綜合評分 /// </summary> public decimal confidence { set; get; } /// <summary> /// 圖片為正常圖片的評分 /// </summary> public decimal hot_score { set; get; } /// <summary> /// 圖片為性感圖片的評分 /// </summary> public decimal normal_score { set; get; } /// <summary> /// 圖片為色情圖片的評分 /// </summary> public decimal porn_score { set; get; } }
public class TencentCloundPicHelper { /// <summary> /// 傳送Post請求騰訊雲 /// </summary> public string SendPost(string postDataStr) { var url = @"http://service.image.myqcloud.com/detection/porn_detect"; try { System.Net.ServicePointManager.Expect100Continue = false; var request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; SetHeaderValue(request.Headers, "content-type", "application/json"); SetHeaderValue(request.Headers, "content-length", postDataStr.Length.ToString()); SetHeaderValue(request.Headers, "Host", "service.image.myqcloud.com"); SetHeaderValue(request.Headers, "authorization", GetSign()); var memStream = new MemoryStream(); var jsonByte = Encoding.GetEncoding("utf-8").GetBytes(postDataStr); memStream.Write(jsonByte, 0, jsonByte.Length); request.ContentLength = memStream.Length; var requestStream = request.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); var response = request.GetResponse(); using (var s = response.GetResponseStream()) { var reader = new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd(); } } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { using (var s = we.Response.GetResponseStream()) { var reader = new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd(); } } else { throw we; } } catch (Exception e) { throw e; } } /// <summary> /// 獲取簽名 /// </summary> public static string GetSign() { var appId = ConfigurationManager.AppSettings["AppId"];//開發者的 APPID,接入智慧影像時由系統生成 var bucket = "tengxunyun";//Bucket,空間名稱,即圖片資源的組織管理單元 var secretId = ConfigurationManager.AppSettings["SecretId"];//Secret ID var secretKey = ConfigurationManager.AppSettings["SecretKey"];//secretKey var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var currentTime = Convert.ToInt64(ts.TotalSeconds);//當前時間戳,是一個符合 UNIX Epoch 時間戳規範的數值,單位為秒,多次簽名時,e 應大於 t var expiredTime = Convert.ToInt64((DateTime.UtcNow.AddMinutes(180) - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);//簽名的有效期,是一個符合 UNIX Epoch 時間戳規範的數值,單位為秒;單次簽名時,e 必須設定為 0 var rand = GetRandom();//隨機串,無符號 10 進位制整數,使用者需自行生成,最長 10 位 var userid = 0;//歷史遺留欄位,請填寫為 0 var fileid = "";//資源儲存的唯一標識,單次簽名必填;多次簽名選填,如填寫則會驗證與當前操作的檔案路徑是否一致。 var encryptText = $"a={appId}&b={bucket}&k={secretId}&e={expiredTime}&t={currentTime}&r={rand}&u=0&f="; var sign = Hmacsha1Encrypt(encryptText, secretKey); return sign; } /// <summary> /// 設定Http post請求頭 /// </summary> public static void SetHeaderValue(WebHeaderCollection header, string name, string value) { var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic); if (property != null) { var collection = property.GetValue(header, null) as NameValueCollection; collection[name] = value; } } /// <summary> /// HMACSHA1演算法加密 /// </summary> private static string Hmacsha1Encrypt(string encryptText, string encryptKey) { using (HMACSHA1 mac = new HMACSHA1(Encoding.UTF8.GetBytes(encryptKey))) { var hash = mac.ComputeHash(Encoding.UTF8.GetBytes(encryptText)); var pText = Encoding.UTF8.GetBytes(encryptText); var all = new byte[hash.Length + pText.Length]; Array.Copy(hash, 0, all, 0, hash.Length); Array.Copy(pText, 0, all, hash.Length, pText.Length); return Convert.ToBase64String(all); } } /// <summary> /// 獲取隨機數 /// </summary> private static int GetRandom() { var random = new Random(); var rand = random.Next(10000, 999999999); return rand; } }