Post data to server and capture response

If you want to post information to a server, capture it and manipulate it, use the code below. If you only want to get the server response for a particular url, click capture url response.

using System.Net;
using System.Text;
using System.IO;

private void OnPostInfoClick(object sender, System.EventArgs e)
{
string strId = UserId_TextBox.Text;
string strName = Name_TextBox.Text;

ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strId;
postData += ("&username="+strName);
byte[] data = encoding.GetBytes(postData);

// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://localhost/MyIdentity/Default.aspx");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();

//Get the response
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
HttpStatusCode status = response.StatusCode;
}

Advertisements

One thought on “Post data to server and capture response

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s