c# post和接收的实现
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;
}
2, WEB接收端
原来那样直接POST出来HTML代码,会返回500错误,原因是“从客户端检测到有潜在危险的Request.Form 值”
解决办法是
1,web.config文件<system.web>后面加入这一句: <pages validateRequest="false"/>
2,在*.ASPx文件头的Page中加入validateRequest="false"
3,遗留问题
1,如果POST"<b>sss</b>"则最后一个"</b>"取不到-_-
2, 如果POST "c=123dsdc=12212&b=dddd" 如果不接收request["b"]则c后面就是第一个等号后所有的东西。把他们区分出来应该对&编码么?可是已经application/x-www-form-urlencoded 了阿。。。。