Go Several ways to post data and receive in C #

Source: Internet
Author: User

Post to submit data, a well-known way:

Use form form submission in HTML page, receive method, use request.form[""] or request.querystring["" "to obtain.

This article introduces another way of post and receiving, which is to submit and receive the whole data as a data stream.

Receiving mode:

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);

You only need to read the byte data from the input stream, and then convert to string, then parse. If you want to reply to the response message only need to use: Response.Write () output (and normal page output).

Active Post Sending method:

            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;            }

Using the HttpClient object to send

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;        }         

From the code can be seen just to convert the string to byte[] type, and added to the request flow, make a request to achieve post effect, this kind of post with the above mentioned on the receiving method used in conjunction with each other.

The following is an active post transfer in the form of a key-value pair.

     <summary>///initiate HttpPost request, can upload file///</summary>//<param name= "url" > Request Address </param>//<param name= "Files" > Files </param>//<param name= "input" > form data </para m>//<param name= "endoding" > Coding </param>//<returns></returns> Public St        Atic 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"); Commit file 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); Item delimiter 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); Add \ r \ n}}//Submit text field if (input! = null) {Strin    G format = "--" + Boundary + "\r\ncontent-disposition:form-data;name=\" {0}\ "\r\n\r\n{1}\r\n"; Bring your own item delimiter                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"); The final delimiter string for the item needs to be brought in-stream. Write (foot_data, 0, Foot_data.            Length); Request. ContentLength = stream.            Length; Stream requeststream = Request. GetRequestStream (); Writes the request data 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; }        }

The main difference between the two types of active post submissions is that the data format before sending is the ContentType value.

Here are a few common contenttype values, and describe their differences

When the Content-type is specified as application/x-www-form-urlencoded, the transmitted data format needs to be as title=test&sub%5b%5d=1&sub%5b%5d=2& Sub%5b%5d=3 the format shown in order to correctly parse

When Content-type is specified as Multipart/form-data, the desired format is shown in the following code block

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 can also be specified as Application/json, and the final transmission format is {"title": "Test", "sub": [All-in-all]} as to how to receive myself without an attempt, However, it can be said that using the receiving method at the beginning of the article will be converted to string type and then

It is possible to send serialization.

The content-type is specified as Text/xml, and the transmitted data format is

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

In this way, I have not tried, accept the way can refer to the Application/json in the above method of reception.

Because of the format of the XML transmission of data, the use of relatively few, I believe many students do not know how to parse the string into an object, the following will provide a conversion method for reference

            XmlDocument doc = new XmlDocument ();            Doc. LOADXML (Weixin);//Read the XML string            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>//        Public account///            </summary> Common            string tousername {get; set;}            <summary>///user account///            </summary> public            string Fromusername {get; set;}            <summary>///Send timestamp///            </summary> public            string Createtime {get; set;}            <summary>/////            </summary> Public            string content {get; set;}            <summary>////            the type of message///            </summary> public            string Msgtype {get; set;}            <summary>///Event name///            </summary> public            string EventName {get; set;}        }

[several ways to post data and receive in]c#]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.