昨天开发过程中用到 HttpWebRequest 需要用POST方式发送XML数据 因为XML数据中带有<或着?等特殊符号所以需要用URLEcode 方法进行编码 同时接收页面应该关闭设置ValidateRequest="false"关闭对请求数据的验证
public string PostAndGetHTML(string targetURL, string param)
{
//formData用于保存提交的信息
string formData =HttpUtility.UrlEncode(param);
formData = "strXml=" + formData;
//把提交的信息转码(post提交必须转码)
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(formData);
//开始创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
request.Method = "POST"; //提交方式:post
request.ContentType ="application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);//将请求的信息写入request
newStream.Close();
try
{
//向服务器发送请求
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.GetEncoding("utf-8"));
string strResult = sr.ReadToEnd();
}
catch
{
}
}