程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#中POST數據和接收的幾種方式(拋磚引玉),

C#中POST數據和接收的幾種方式(拋磚引玉),

編輯:C#入門知識

C#中POST數據和接收的幾種方式(拋磚引玉),


POST方式提交數據,一種眾所周知的方式:

html頁面中使用form表單提交,接收方式,使用Request.Form[""]或Request.QueryString[""]來獲取。

 

這裡介紹另外一種POST方式和接收方式,就是將整個數據作為加入到數據流中提交和接收

接收方式:

Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
return Encoding.UTF8.GetString(b);

只需要從input Stream中讀取byte數據,然後轉為string,再解析即可。如果要回復響應消息只需要用:Response.Write()  輸出即可(和普通的頁面輸出一樣)。

 

主動POST發送方式:

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.Method = "post";


            byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();



            using (var httpWebResponse = webrequest.GetResponse())
            using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
            {

                String ret = responseStream.ReadToEnd();

                T result = XmlDeserialize<T>(ret);

                return result;
            }

使用HttpClient對象發送

 public static  string   PostXmlResponse(string url, string xmlString)
             
        {
            HttpContent httpContent = new StringContent(xmlString);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpClient httpClient = new HttpClient();

           

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                return t.Result;
            }
            return string.Empty;
        }
         

 

從代碼中可以看出僅僅是將字符串轉為byte[] 類型,並加入到請求流中,進行請求即可達到POST效果,該種POST方式與上邊所提到的接收方式相互配合使用。

下面一種方式是以鍵值對的方式主動POST傳輸的。

 

     /// <summary>
        /// 發起httpPost 請求,可以上傳文件
        /// </summary>
        /// <param name="url">請求的地址</param>
        /// <param name="files">文件</param>
        /// <param name="input">表單數據</param>
        /// <param name="endoding">編碼</param>
        /// <returns></returns>
        public static string PostResponse(string url, UpLoadFile[] files, Dictionary<string, string> input, Encoding endoding)
        {

            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            //request.Credentials = CredentialCache.DefaultCredentials;
            request.Expect = "";

            MemoryStream stream = new MemoryStream();


            byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            byte[] enterER = Encoding.ASCII.GetBytes("\r\n");
            ////提交文件
            if (files != null)
            {
                string fformat = "Content-Disposition:form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
                foreach (UpLoadFile file in files)
                {

                    stream.Write(line, 0, line.Length);        //項目分隔符
                    string s = string.Format(fformat, file.Name, file.FileName, file.Content_Type);
                    byte[] data = Encoding.UTF8.GetBytes(s);
                    stream.Write(data, 0, data.Length);
                    stream.Write(file.Data, 0, file.Data.Length);
                    stream.Write(enterER, 0, enterER.Length);  //添加\r\n
                }
            }


            //提交文本字段
            if (input != null)
            {
                string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n";    //自帶項目分隔符
                foreach (string key in input.Keys)
                {
                    string s = string.Format(format, key, input[key]);
                    byte[] data = Encoding.UTF8.GetBytes(s);
                    stream.Write(data, 0, data.Length);
                }

            }

            byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");      //項目最後的分隔符字符串需要帶上--  
            stream.Write(foot_data, 0, foot_data.Length);



            request.ContentLength = stream.Length;
            Stream requestStream = request.GetRequestStream(); //寫入請求數據
            stream.Position = 0L;
            stream.CopyTo(requestStream); //
            stream.Close();

            requestStream.Close();



            try
            {


                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();

                    try
                    {
                        using (var responseStream = response.GetResponseStream())
                        using (var mstream = new MemoryStream())
                        {
                            responseStream.CopyTo(mstream);
                            string message = endoding.GetString(mstream.ToArray());
                            return message;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                catch (WebException ex)
                {
                    //response = (HttpWebResponse)ex.Response;


                    //if (response.StatusCode == HttpStatusCode.BadRequest)
                    //{
                    //    using (Stream data = response.GetResponseStream())
                    //    {
                    //        using (StreamReader reader = new StreamReader(data))
                    //        {
                    //            string text = reader.ReadToEnd();
                    //            Console.WriteLine(text);
                    //        }
                    //    }
                    //}

                    throw ex;
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

通過兩種主動POST提交 的代碼可以看出,其主要區別在於發送前的數據格式 ContentType 的值。

下面列舉幾種常用的ContentType 值,並簡述他們的區別

Content-Type 被指定為 application/x-www-form-urlencoded 時候,傳輸的數據格式需要如  title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3 所示格式,才能正確解析

Content-Type 被指定為 multipart/form-data 時候,所需格式如下面代碼塊中所示

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA

------WebKitFormBoundaryrGKCBY7qhFd3TrwA

Content-Disposition: form-data; name="text"

title

------WebKitFormBoundaryrGKCBY7qhFd3TrwA

Content-Disposition: form-data; name="file"; filename="chrome.png"

Content-Type: image/png

PNG ... content of chrome.png ...

------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

Content-Type 也可以被指定為 application/json ,最終傳輸格式為 {"title":"test","sub":[1,2,3]}  至於如何接收本人未經嘗試,但是可以肯定的講使用文章開頭所說的接收方式接收後轉為string類型再

發序列化是可行的。

 

Content-Type指定為 text/xml  ,傳輸的數據格式為

<?xml version="1.0"?>
<methodCall>
    <methodName>examples.getStateName</methodName>
    <params>
        <param>
            <value><i4>41</i4></value>
        </param>
    </params>
</methodCall>

此種方式,本人亦未經嘗試,接受方式可以參考上文中 application/json 的接收方式。

由於xml的格式傳輸數據,使用相對較少,相信很多同學亦不知道如何將字符串解析為對象,下文將提供一種轉換方式,供參考

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixin);//讀取xml字符串
            XmlElement root = doc.DocumentElement;

            ExmlMsg xmlMsg = new ExmlMsg()
            {
                FromUserName = root.SelectSingleNode("FromUserName").InnerText,
                ToUserName = root.SelectSingleNode("ToUserName").InnerText,
                CreateTime = root.SelectSingleNode("CreateTime").InnerText,
                MsgType = root.SelectSingleNode("MsgType").InnerText,
            };
            if (xmlMsg.MsgType.Trim().ToLower() == "text")
            {
                xmlMsg.Content = root.SelectSingleNode("Content").InnerText;
            }
            else if (xmlMsg.MsgType.Trim().ToLower() == "event")
            {
                xmlMsg.EventName = root.SelectSingleNode("Event").InnerText;
            }
            return xmlMsg;
        private class ExmlMsg
        {
            /// <summary>
            /// 本公眾賬號
            /// </summary>
            public string ToUserName { get; set; }
            /// <summary>
            /// 用戶賬號
            /// </summary>
            public string FromUserName { get; set; }
            /// <summary>
            /// 發送時間戳
            /// </summary>
            public string CreateTime { get; set; }
            /// <summary>
            /// 發送的文本內容
            /// </summary>
            public string Content { get; set; }
            /// <summary>
            /// 消息的類型
            /// </summary>
            public string MsgType { get; set; }
            /// <summary>
            /// 事件名稱
            /// </summary>
            public string EventName { get; set; }

        }

 

至此,相信一部分同學能有所得。由於本人水平一般,文中所述可能有纰漏之處,還請路過高手指出,同時也歡迎在評論區貼出更好的 發送和接受方式,供大家學習和交流。

本文有參考:https://imququ.com/post/four-ways-to-post-data-in-http.html  ,向原文作者致謝。

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved