G’day Fellas,
Many a times we have to do a HTTP POST to one of our websites either to push something or to push and get something in return.
Below is the code that I use to make such calls.
c# code
[geshi lang=”csharp” nums=”1″ target=”_self” ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
string params = ""; // just simulating with some data params += "Email=jas@jc.org&"; params += "Passwd=mysupersecpwd"; byte[] byteArray = Encoding.UTF8.GetBytes(params); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://yourdomain.com/post.php"); // change this URL to meet your requirement webRequest.Method = "POST"; // important when posting webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); try { HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); if (HttpStatusCode.OK == response.StatusCode) { dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); String responseStr = reader.ReadToEnd(); Console.WriteLine(responseStr); response.Close(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } |
You can put this code inside a function of your say Util class and reuse this code again and again.
I hope this helps
Cheers
[sam_ad id=”54″ codes=”true”]
Leave a Reply