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!
Related posts:
- Objective-C: Base64 to NSString and NSString to Base64 While working on the CSCW Lab project, I encountered...
- Wordpress – How to Delete Existing Post Revisions This is the second part of managing Wordpress feature...
- Wordpress – managing Post Revisions Tracking A very interesting feature added in WordPress is the post...
- Tweet your ideas through JavaScript Do you have a website and would like to post...
- Change Browser’s UserAgent The question of What’s that user agent string used for?...
Euro
Lira sterlina
Dolar SUA
Francul elvetian
Gramul de aur



