WebClient 不支持超时设定,这一点太糟糕了。因此选用HttpWebRequest代替WebClient :
HttpWebRequest毕竟是WebClient 的父类,因此POST起来比较麻烦。
try
{
string valpairs="";
valpairs="c="+textBox1.Text;
UTF8Encoding encoding=new UTF8Encoding();
b = encoding.GetBytes(valpairs);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/t/default.aspx");
request.Timeout=1000*5;
request.Method = "POST";
request.ContentType="application/x-www-form-urlencoded";
request.ContentLength=b.Length;
request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
上面这一大串就POST完了。比WebClient麻烦不少,不过仔细一看 这些乱七八糟语言都差不多哈,尤其是这句"application/x-www-form-urlencoded";真是哪都有用,在ASP里FORM头定义POST/GET的时候用过,用AJAX POST的时候也用过。
下面是接收返回信息,与本主题无关,留在这里保证代码的完整性。
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode==HttpStatusCode.OK)
{
Stream resStream = response.GetResponseStream();
System.IO.StreamReader streamReader = new StreamReader(resStream, System.Text.Encoding.GetEncoding("UTF-8"));
string content = streamReader.ReadToEnd();
//textBox1.Text = content;
streamReader.Close();
resStream.Close();
}
}
catch(Exception err)
{
textBox1.Text = "1:" + err.Message;
}