阿里雲人臉屬性API,我已經迷惑無比了!

想學習一下阿里的人臉識別API,Java版的參照https://help.aliyun.com/document_detail/67818.html?spm=a2c4g.11186623.6.559.a31e4bd9BDsnO9 已經沒有問題,成功了。當我把這些代碼轉換爲C#時,說死是不成功啊。
Java版中只是把其中的main函數改了一下,如下:

    public static void main(String[] args) throws Exception {
        setProxyofNeusoft();
        // 發送POST請求示例
        String ak_id = "my ak_id"; // 用戶ak
        String ak_secret = "my secret"; // 用戶ak_secret
        String url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute";
        
        String body = "{\"type\": \"0\", \"image_url\":\"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540359146297&di=3218a5eefe6b89b990144478fe078e25&imgtype=0&src=http%3A%2F%2Fhimg2.huanqiu.com%2Fattachment2010%2F2015%2F0311%2F20150311030317329.jpg\"}";
        // String body = "{\"type\": \"1\", \"content\":\"xxx\"}";
        System.out.println("response body:" + sendPost(url, body, ak_id, ak_secret));
        
        body = "{\"type\": \"1\", \"content\":\"" + Base64.getEncoder().encodeToString(toByteArray("E:\\0531\\face\\WIN_20181023_16_31_35_Pro.jpg")) + "\"}";
        System.out.println("response body:" + sendPost(url, body, ak_id, ak_secret));
        
    }

當我使用C#來實現時,打死不成功啊。
Main函數如下:

static void Main(string[] args)
        {
            string ak_id = "my ak_id"; // 用戶ak
            string ak_secret = "my secret"; // 用戶ak_secret
            string url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute";
            // 通過URL判斷
            string body = "{\"type\": \"0\", \"image_url\":\"http://g.hiphotos.baidu.com/image/pic/item/730e0cf3d7ca7bcb944f655cb3096b63f624a889.jpg\"}";          
            Console.WriteLine("response body:" + DoPost(url, body, ak_id, ak_secret));
            Console.ReadLine();
        }

其中的DoPost函數如下:

public static string DoPost(string url, string body, string ak_id, string ak_secret)
        {             
            string result = string.Empty;
            HttpClient httpClient = new HttpClient();

            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");

            DateTime dateNow = DateTime.Now;
            string bodyMd5 = MD5Base64(body);
            string method = "POST";
            string accept = "application/json";
            string content_type = "application/json";
            string date = ToGMTstring(dateNow);

            HttpContent httpContent = new StringContent(bodyMd5);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //設置Http的內容標頭的字符
            //httpContent.Headers.ContentType.CharSet = "utf-8";
            httpClient.DefaultRequestHeaders.Date = dateNow;
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
            string stringToSign = method + "\\n" + accept + "\\n" + bodyMd5 + "\\n" + content_type + "\\n" + date + "\\n"
                   + "/face/attribute";
            // 2.計算 HMAC-SHA1
            string signature = HMACSha1(stringToSign, ak_secret);
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Dataplus", ak_id + ":" + signature);
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            Console.WriteLine(response.StatusCode);
            result = response.Content.ReadAsStringAsync().Result;
            return result;
        }

引用的計算MD5和SHA的函數轉換爲C#如下:

public static string ToGMTstring(DateTime date)
        {
            return date.ToUniversalTime().ToString("r");
        }

        /// 計算MD5+BASE64
        public static string MD5Base64(string s)
        {
            if (s == null)
                return null;
            string encodeStr = "";
            byte[] utfBytes = System.Text.Encoding.UTF8.GetBytes(s);
            MD5 md5 = new MD5CryptoServiceProvider();
            try
            {
                byte[] md5Bytes = md5.ComputeHash(utfBytes);
                encodeStr = Convert.ToBase64String(md5Bytes);
            }
            catch (Exception e)
            {
                throw new Exception("Failed to generate MD5 : " + e.Message);
            }
            return encodeStr;
        }


        /// 計算 HMAC-SHA1
        public static string HMACSha1(string data, string key)
        {
            try
            {
                HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
                byte[] byteText = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(data));
                return System.Convert.ToBase64String(byteText);
            }
            catch (Exception e)
            {
                throw new Exception("Failed to generate HMAC : " + e.Message);
            }
        }

很鬱悶的就是調用不成功,取得的響應內容是
response body:The authorization(Dataplus my_ak_id:my_signature) of this request Invalid! {"url":"/face/attribute","headers":{"date":"Wed, 24 Oct 2018 05:50:10 GMT","accept":"application/json","authorization":"Dataplus my_ak_id:my_signature","content-type":"application/json"},"method":"POST"}
{"url":"/face/attribute","headers":{"date":"Wed, 24 Oct 2018 05:50:10 GMT","accept":"application/json","authorization":"Dataplus my_ak_id:my_signature","content-type":"application/json"},"method":"POST"}

其中輸出已做替換my_ak_id:my_signature實際輸出是我的ak_id和計算的簽名。

在大佬在嗎?指導一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章