Tuesday, November 8, 2011

How to post data and get data with HttpWebRequest and HttpWebResponse in asp.net

Put the shown below code in code-behind.

protected string PostAndReadDataFromUrl()

{

string para = "";

string retVal = "";

string targetUrl = "";

try

{

targetUrl = "http://test.iblogseeker.com/test.aspx";

para = string.Format("dataRequest={0}", "This is test.");

HttpWebResponse webRes = null;

HttpWebRequest webReq;

webReq = (HttpWebRequest)WebRequest.Create(targetUrl);

webReq.Method = "POST";

webReq.ContentType = "application/x-www-form-urlencoded";

string postData = para;

byte[] bytes = Encoding.ASCII.GetBytes(postData);

Stream os = null;

webReq.ContentLength = bytes.Length;

os = webReq.GetRequestStream();

os.Write(bytes, 0, bytes.Length);

webRes = (HttpWebResponse)webReq.GetResponse();

StreamReader streamRdr = new StreamReader(webRes.GetResponseStream());

retVal = streamRdr.ReadToEnd();

}

catch (Exception ex)

{

retVal = "";

}

return retVal;

}


Enjoy the programming! :)

No comments:

Post a Comment