C# .Net using Post with HTTPWebRequest


Microsoft Surface - Programming with C# and using WCF / WPF and Silverlight

Just a reminder for posterity : posting with .Net its so easy! Check out the Cocoa touch framework to  realize the  difference!

 

 
 public string Post(string url, string data) {
  string strReturn = null;
  try
  {
	  //Encoding the post vars
	  byte[] buffer = Encoding.ASCII.GetBytes(data);
	  //Initialisation with provided url
	  HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
	  
	  //Set method to post, otherwise postvars will not be used
	  WebReq.Method = "POST";
	  WebReq.ContentType = "application/x-www-form-urlencoded";
	  WebReq.ContentLength = buffer.Length;
	  Stream PostData = WebReq.GetRequestStream();
	  PostData.Write(buffer, 0, buffer.Length);
	  //Closing is always important
	  PostData.Close();
	  
	  //Get the response handle, we have no true response yet
	  HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
	  
	  //information about the response
	  HTTPStatusCode status = WebResp.StatusCode;
	  string server = WebResp.Server;

	  //read the response 
	  Stream WebResponse = WebResp.GetResponseStream();
	  StreamReader _response = new StreamReader(WebResponse);
	  strReturn =  _response.ReadToEnd();
  }
  catch (Exception ex)
  {
	  MessageBox.Show(ex.Message);
  }
  
  return strReturn.Trim();
}

Enjoy!

Leave a comment

Your email address will not be published. Required fields are marked *