C# .Net using Post with HTTPWebRequest
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!
| Print article | This entry was posted by Radu Poenaru on 8 August 2009 at 2:26 pm, and is filed under My work. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

