1、发起请求
下面这个方法的作用就是接收要发送的数据及数据要发送到的URL,然后返回响应数据
protected string SendRequest(string data,string url)
{
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] sendBytes = Encoding.UTF8.GetBytes(data);
req.ContentLength = sendBytes.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(sendBytes, 0, sendBytes.Length);
reqStream.Close();
WebResponse res = req.GetResponse();
Stream resStream = res.GetResponseStream();
StreamReader sr = new StreamReader(resStream, Encoding.UTF8);
string resData = sr.ReadToEnd();
sr.Close();
resStream.Close();
return resData;
}
使用示例:
protected void btnSubscribe_Click(object sender, EventArgs e)
{
string FileName = Server.MapPath("订购.xml");
FileStream fs = new FileStream(FileName, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string ReqData = sr.ReadToEnd();
sr.Close();
fs.Close();
txtResponse.Text = SendRequest(ReqData, "http://localhost:2102/InterWeb/subscribe.htm");
}
2、处理请求
接收要简单一些,用下面这两句代码就可以了
StreamReader sr = new StreamReader(Request.InputStream);
ReqData = sr.ReadToEnd();
3、总结
这种处理方式一般会用在一些对外的接口等的开发中,以XML传递协议数据。