Tuesday, July 12, 2005

C# Get result of a web page with POST variables

public static string HttpPOSTConnection(string strUrl,string Param)
{
string strResponse = "";
try
{
string postData = Param;
byte[] byte1=System.Text.Encoding.Default.GetBytes(postData);
// Set the content type of the data being posted.
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
webRequest.Method = "POST";
webRequest.ContentType="application/x-www-form-urlencoded";
// Set the content length of the string being posted.
webRequest.ContentLength=byte1.Length;
System.IO.Stream newStream=webRequest.GetRequestStream();
newStream.Write(byte1,0,byte1.Length);

System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("big5");
System.IO.Stream stream = webResponse.GetResponseStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, System.Text.Encoding.Default);
strResponse = streamReader.ReadToEnd();

//-----release the reader and stream resource-----
newStream.Close();
streamReader.Close();
stream.Close();
}
catch(Exception exp)
{
throw exp;
}
return strResponse;
}

No comments: