1. 程式人生 > >曠視Face++的Api學習

曠視Face++的Api學習

1、http處理類

 public static class HttpHelper4MultipartForm
    {
        
        public class FileParameter //檔案類,之後會用於判斷傳輸的是圖片路徑,還是圖片base64編碼,還是二進位制格式
        {
            public byte[] File
            {
                get;
                set;
            }
            public string FileName
            {
                get;
                set;
            }
            public string ContentType
            {
                get;
                set;
            }
            public FileParameter(byte[] file) : this(file, null)
            {
            }
            public FileParameter(byte[] file, string filename) : this(file, filename, null)
            {
            }
            public FileParameter(byte[] file, string filename, string contenttype)
            {
                this.File = file;
                this.FileName = filename;
                this.ContentType = contenttype;
            }
        }
        private static readonly Encoding encoding = Encoding.UTF8;//確定傳輸編碼
        /// <summary>
        /// MultipartForm請求
        /// </summary>
        /// <param name="postUrl">服務地址</param>
        /// <param name="userAgent"></param>
        /// <param name="postParameters">引數</param>
        /// <returns></returns>
        public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
        {
            string text = string.Format("----------{0:N}", Guid.NewGuid());//全域性標識碼,將會得到----------加上以分號分隔的全域性標識碼,如----------250,000為啥有這麼多-,我也不知道
            string contentType = "multipart/form-data; boundary=" + text;//multipart型別
            byte[] multipartFormData = HttpHelper4MultipartForm.GetMultipartFormData(postParameters, text);
            return HttpHelper4MultipartForm.PostForm(postUrl, userAgent, contentType, multipartFormData);
        }

        private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
        {
            HttpWebRequest httpWebRequest = WebRequest.Create(postUrl) as HttpWebRequest;
            if (httpWebRequest == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            httpWebRequest.Method = "POST";//post方式
            httpWebRequest.SendChunked = false;
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Proxy = null;
            httpWebRequest.Timeout = Timeout.Infinite;
            httpWebRequest.ReadWriteTimeout = Timeout.Infinite;
            httpWebRequest.AllowWriteStreamBuffering = false;
            httpWebRequest.ProtocolVersion = HttpVersion.Version11;
            httpWebRequest.ContentType = contentType;
            httpWebRequest.CookieContainer = new CookieContainer();
            httpWebRequest.ContentLength = (long)formData.Length;

            try
            {
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    int bufferSize = 4096;
                    int position = 0;
                    while (position < formData.Length)
                    {
                        bufferSize = Math.Min(bufferSize, formData.Length - position);
                        byte[] data = new byte[bufferSize];
                        Array.Copy(formData, position, data, 0, bufferSize);
                        requestStream.Write(data, 0, data.Length);
                        position += data.Length;
                    }
                    requestStream.Close();
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            HttpWebResponse result;
            try
            {
                result = (httpWebRequest.GetResponse() as HttpWebResponse);
            }
            catch (WebException arg_9C_0)
            {
                result = (arg_9C_0.Response as HttpWebResponse);
            }
            return result;
        }
 public static byte[] getBytePicture(string path)
        {
            Bitmap bmp = new Bitmap(path); // 圖片地址
            byte[] fileImage;
            using (Stream stream1 = new MemoryStream())
            {
                bmp.Save(stream1, ImageFormat.Jpeg);
                byte[] arr = new byte[stream1.Length];
                stream1.Position = 0;
                stream1.Read(arr, 0, (int)stream1.Length);
                stream1.Close();
                fileImage = arr;
            }
            return fileImage;
        }
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)//檢查驗證結果,額,,,,我覺得這裡應該有其它東西要寫的
        {
            return true;
        }
        /// <summary>
        /// 從表單中獲取資料
        /// </summary>
        /// <param name="postParameters"></param>
        /// <param name="boundary"></param>
        /// <returns></returns>
        private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
        {
            Stream stream = new MemoryStream();
            bool flag = false;
            foreach (KeyValuePair<string, object> current in postParameters)
            {
                if (flag)
                {
                    stream.Write(HttpHelper4MultipartForm.encoding.GetBytes("\r\n"), 0, HttpHelper4MultipartForm.encoding.GetByteCount("\r\n"));
                }
                flag = true;
                if (current.Value is HttpHelper4MultipartForm.FileParameter)
                {
                    HttpHelper4MultipartForm.FileParameter fileParameter = (HttpHelper4MultipartForm.FileParameter)current.Value;
                    string s = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", new object[]
                    {
                        boundary,
                        current.Key,
                        fileParameter.FileName ?? current.Key,
                        fileParameter.ContentType ?? "application/octet-stream"
                    });
                    stream.Write(HttpHelper4MultipartForm.encoding.GetBytes(s), 0, HttpHelper4MultipartForm.encoding.GetByteCount(s));
                    stream.Write(fileParameter.File, 0, fileParameter.File.Length);
                }
                else
                {
                    string s2 = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, current.Key, current.Value);//
                    stream.Write(HttpHelper4MultipartForm.encoding.GetBytes(s2), 0, HttpHelper4MultipartForm.encoding.GetByteCount(s2));
                }
            }
            string s3 = "\r\n--" + boundary + "--\r\n";
            stream.Write(HttpHelper4MultipartForm.encoding.GetBytes(s3), 0, HttpHelper4MultipartForm.encoding.GetByteCount(s3));
            stream.Position = 0L;
            byte[] array = new byte[stream.Length];
            stream.Read(array, 0, array.Length);
            stream.Close();
            return array;
        }
    }



GetMultipartFormData
表單中獲取的資料例項(以detect舉例)

--multipart/form-data; boundary=----------{Guid全域性標識碼}
Content-Disposition: form-data; name="api_id"

api_id的值"
--multipart/form-data; boundary=----------{Guid全域性標識碼}
Content-Disposition: form-data; name="api_secret"

api_secret的值"
--multipart/form-data; boundary=----------{Guid全域性標識碼}
Content-Disposition: form-data; name="其他引數"

其他引數的值"
--multipart/form-data; boundary=----------{Guid全域性標識碼}
Content-Disposition: form-data; name="image_file(圖片型別)"; filename="圖片名字??image_file(圖片型別)"
Content-Type: 請求主體的內容是如何編碼 ?? application/octet-stream

圖片的二進位制編碼
--multipart/form-data; boundary=----------{Guid全域性標識碼}--

。。。//這裡表示一個空行,必須有這一行


 //呼叫示例
 //引數字典
           

 Dictionary<string, object> verifyPostParameters = new Dictionary<string, object>();
            verifyPostParameters.Add("api_key", “你的apikey”);
            verifyPostParameters.Add("api_secret", "你的apisecret");
            verifyPostParameters.Add("return_landmark", "1");
            verifyPostParameters.Add("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
            verifyPostParameters.Add("calculate_all", "1");


            byte[] fileImage = HttpHelper4MultipartForm.getBytePicture(@"C:\2.jpg");
            //新增圖片引數
            verifyPostParameters.Add("image_file", new HttpHelper4MultipartForm.FileParameter(fileImage, "2.jpg", "application/octet-stream"));
            HttpWebResponse verifyResponse = HttpHelper4MultipartForm.MultipartFormDataPost("https://api-cn.faceplusplus.com/facepp/v3/detect", "", verifyPostParameters);
        
            Stream str = verifyResponse.GetResponseStream();
            StreamReader str1 = new StreamReader(str);
            string xx = str1.ReadToEnd();
            JObject ja = (JObject)JsonConvert.DeserializeObject(xx);//轉換為jobject格式            FaceDeteClass result1 = ja.ToObject<FaceDeteClass>();
      textBox1.Text += ja.ToString();//將結果轉換為string格式

json類生成方法,把string結果輸入到這個網址https://www.bejson.com/convert/json2csharp/

然後可以生成c#類,準確率挺高的,就是裡面一堆垃圾程式碼註釋,得用word通過替換的方式刪掉。