網絡數據請求request

關於網絡數據請求的類不少,httpwebrequest,webrequest,webclient以及httpclient,具體差異在此不在贅述,在應用方面介紹webclient與httpclient則顯得比較比較簡單粗暴,httpwebrequest繼承自webrequest,可經過參數進行請求控制。html

1)基於WebClient的post/get數據請求:web

getjson

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.GetEncoding("utf-8");
                var responseString = client.DownloadString("http://www.sojson.com/open/api/weather/json.shtml?city=閔行區");
     
                Console.WriteLine(responseString);
                Console.ReadKey();
            }

postapi

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.GetEncoding("utf-8");
                var values = new NameValueCollection();
                values["api_key"] = "**********";
                values["api_secret"] = "**********";
                values["image_url"] = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508759666809&di=b3748df04c5e54d18fe52ee413f72f37&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F562c11dfa9ec8a1389c45414fd03918fa1ecc06c.jpg";

                var response = client.UploadValues("https://api-cn.faceplusplus.com/facepp/v3/detect", values);

                var responseString = Encoding.Default.GetString(response);
                Console.WriteLine(responseString);
                Console.ReadKey();
            }

 

 2)基於HttpWebRequest 的get/post方法網絡

getapp

 

  /// <summary>
        /// get
        /// </summary>
        /// <param name="url">url="http:**********"+"?"+"key1=***&key2=***"</param>
        /// example :http://www.sojson.com/open/api/weather/json.shtml?city=閔行區
        /// <returns></returns>
        public static string GetHttp(string url)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";
            httpWebRequest.Timeout = 20000;

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();

            return responseContent;
        }

 

 

postpost

post提交數據的方式有四種,具體體如今contentType有四種方式:application/x-www-form-urlencoded,multipart/form-data,application/json以及text/xml,本文主講前兩種方法,第三種即爲經過json格式發送數據,第四種經過xml格式發送。ui

(一)contentType=application/x-www-form-urlencodedurl

此種方式應用比較廣泛,可是當傳遞參數中存在文件如圖片時則須要用到multipart/form-data方式spa

       /// <summary>
        /// 採用httpwebrequest post方法請求數據
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body">body是要傳遞的參數,格式:api_keyi=xxxxxx&api_secret=xxxxxxx</param>
        /// <param name="contentType">application/x-www-form-urlencoded</param>
        /// <returns></returns>
        public static string PostHttpWebRequest(string url, string body, string contentType)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = contentType; 
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 1000;

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();
            httpWebResponse.Close();

            return responseContent;
        }

 

(二)contentType=multipart/form-data

 此種方式請求數據時,請求的數據流比較繁瑣,須要本身來肯定,即httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);中的btBodys須要本身構造,比較繁瑣。其構造主體以下所示:

HTTP請求頭:
....
multipart/form-data; charset=utf-8;boundary=AaB03x //boundary=AaB03x爲下文請求體中用於分隔不一樣請求參數的文本邊界請求頭能夠放在請求數據流中,也能夠直接在contentType中定義即contentType=multipart/form-data; charset=utf-8;boundary=AaB03x
....


HTTP請求體:
--AaB03x                                                                  //第一個參數邊界:即在請求頭中boundary文本AaB03x前加‘’--‘’
Content-Disposition: form-data; name="key1"         //換行,在此加入數據的第一個參數名稱
                                                                                //繼續換行(即空一行)
value1                                                                     //添加第一個參數對應的值
--AaB03x                                                                 //第二個參數邊界:即在請求頭中boundary文本AaB03x前加‘’--‘’,字符串參數格式均與上同
Content-disposition: form-data; name="key2"             

value2
--AaB03x                                                                  //邊界,此處添加圖片
Content-disposition: form-data; name="key3"; filename="file"    // filename表示文件名,其值與是否爲真實文件名無關
Content-Type: application/octet-stream                   // 表示文件形式,這也是與字符串參數的不一樣

圖片數據                                                                  // 圖片數據,爲二進制byte類型數據
--AaB03x--                                                               //結束邊界,爲boundary文本值AaB03x先後各加加‘’--‘’

 

PS:

1)邊界boundary的值未不會重複的字符串,大小等因素基本沒影響,通常採用boundary = string.Format("{0}", Guid.NewGuid());生成,或者採用時間參數如boundary =DateTime.Now.Ticks.ToString();

 

代碼以下

    class RequestForm
    {
        public class PostImage  //image
        {
            public string fullPath;
            public string imageName; 
            public string contentType= "application/octet-stream";

            public PostImage(string path)
            {
                fullPath = path;
                imageName = Path.GetFileName(path);
            }            
        }

        class PostFile //files
        {

        }

        private static readonly Encoding encoding = Encoding.UTF8;


        /// <summary>
        /// 調用入口
        /// </summary>
        /// <param name="postParameter"></param>
        /// <param name="url"></param>
        /// <returns></returns>
public static string OnRequest(Dictionary<string,object> postParameter,string url)//主調用程序 { string boundary = string.Format("{0}", Guid.NewGuid()); byte[] body=GetPostForm(postParameter, boundary); string contentType = "multipart/form-data; boundary=" + boundary; return OnWebRequest(body, url, contentType); //return PostForm(url, contentType, body); } private static byte[] GetPostForm(Dictionary<string, object> postParameter,string boundary)//獲取請求主體 { Stream stream = new MemoryStream(); bool isFirstPara = false; foreach (KeyValuePair<string, object> para in postParameter) { if (isFirstPara) { stream.Write(encoding.GetBytes("\r\n"), 0,encoding.GetByteCount("\r\n")); } isFirstPara = true; //若須要添加文件信息如txt等增長else分支添加 if (para.Value is PostImage) { PostImage postImage = (PostImage)para.Value; string imageStatement = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", new object[] { boundary, para.Key, postImage.imageName??para.Key, postImage.contentType??"application/octet-stream" }); stream.Write(encoding.GetBytes(imageStatement), 0, encoding.GetByteCount(imageStatement)); byte[] imageContent = GetImageInfo(postImage.fullPath); stream.Write(imageContent, 0, imageContent.Length); } else { string regularStatement = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, para.Key, para.Value); stream.Write(encoding.GetBytes(regularStatement), 0, encoding.GetByteCount(regularStatement)); } } string end = "\r\n--" + boundary + "--\r\n"; stream.Write(encoding.GetBytes(end), 0, encoding.GetByteCount(end)); stream.Position = 0L; byte[] bodyArr = new byte[stream.Length]; stream.Read(bodyArr, 0, bodyArr.Length); stream.Close(); return bodyArr; } private static string OnWebRequest(byte[] postForm,string url,string contentType)//數據請求 { HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url); //try //{ // HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //} //catch(WebException ex) //{ // return ex.Message; //} if (request == null) return "Failed to connect url"; request.Method = "POST"; request.Timeout =2000; request.ReadWriteTimeout =2000; request.ContentType = contentType; request.ContentLength = (long)postForm.Length; try { using (Stream requestStream = request.GetRequestStream()) { int bufferSize = 4096; int position = 0; while (position < postForm.Length) { bufferSize = Math.Min(bufferSize, postForm.Length - position); byte[] data = new byte[bufferSize]; Array.Copy(postForm, position, data, 0, bufferSize); requestStream.Write(data, 0, data.Length); position += data.Length; } //requestStream.Write(formData, 0, formData.Length); requestStream.Close(); } } catch (Exception ex) { return ex.Message; } HttpWebResponse result; try { result = (HttpWebResponse)(request.GetResponse()); } catch (Exception ex) { return ex.Message; } StreamReader streamReader = new StreamReader(result.GetResponseStream()); return streamReader.ReadToEnd(); } private static byte[] GetImageInfo(string path)//經過路徑獲取圖片信息 { Bitmap bmp = new Bitmap(path); byte[] imageInfo; using (Stream stream = new MemoryStream()) { bmp.Save(stream,ImageFormat.Jpeg); byte[] arr = new byte[stream.Length]; stream.Position = 0; stream.Read(arr, 0, (int)stream.Length); stream.Close(); imageInfo = arr; } return imageInfo; } }

調用代碼:

        static void Main(string[] args)
        {
            string imagePath = @"D:\test\image\1.jpg";
            string url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
            RequestForm.PostImage postImage = new RequestForm.PostImage(imagePath);

            Dictionary<string, object> postParameter = new Dictionary<string, object>();
            postParameter.Add("api_key", "*************************");
            postParameter.Add("api_secret", "**************************");
            postParameter.Add("image_file", postImage);
            //postParameter.Add("image_url", "http://imgtu.5011.net/uploads/content/20170328/7150651490664042.jpg");

            string result = RequestForm.OnRequest(postParameter, url);
            Console.WriteLine(result);
            Console.ReadKey();
        }

調用時參數爲請求的url以及Dictionary<string, object> 類型的主體參數,傳入圖片時只須要一個參數調用時的key(上述代碼爲"image_file")和包含圖片路徑的對象postImage,若是傳入參數還須要其餘文件如Txt格式等的文件時,只須要經過filestream讀取出來便可

相關文章
相關標籤/搜索