On occasion it is necessary to post data via an HTTP POST to another page as though that post was submitted by a user but without the user’s interaction. In order to accomplish this use the following code:
private void PostForm()
{
WebRequest request = WebRequest.Create(_targetUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postContent = string.Format("parameter1={0}¶meter2={1}", _parameter1, _parameter2);
byte[] postContentBytes = Encoding.ASCII.GetBytes(postContent);
request.ContentLength = postContentBytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(postContentBytes, 0, postContentBytes.Length);
writer.Close();
HttpWebResponse testResponse = (HttpWebResponse)request.GetResponse();
if (!testResponse.StatusDescription.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
{
//TODO: Handle failure
}
}
Published by