I’ve decided to start a quick tip series on this blog. I’ll try to post some useful code snippets along with some tips and tricks that I’ve learned throughout the years.
This first quick tip shows you how to do a simple HTTP Post in MonoTouch.
You can download the example solution here.
public static string HttpPost(string url, string parameters)
//Create a WebRequest
WebRequest req = WebRequest.Create(url);
//Set the content type and method
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//Get the total size of the post parameters and set the content length
byte  bytes = System.Text.Encoding.UTF8.GetBytes(parameters);
req.ContentLength = bytes.Length;
//Write the data to the request stream
Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length);
//Get the response
WebResponse resp = req.GetResponse();
if (resp== null) return null;
//Get the response stream and read the response
StreamReader sr = new StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd().Trim();
//Close the streams
The download also includes a sample PHP page that you can use for testing the POST.