[轉]C#中POST資料和接收的幾種方式

來源:互聯網
上載者:User

標籤:ada   bsp   time   toolbar   方式   osi   介紹   row   區別   

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------WebKitFormBoundaryrGKCBY7qhFd3TrwAContent-Disposition: form-data; name="text"title------WebKitFormBoundaryrGKCBY7qhFd3TrwAContent-Disposition: form-data; name="file"; filename="chrome.png"Content-Type: image/pngPNG ... 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; }        }

[轉]C#中POST資料和接收的幾種方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.