ASP.NET 中接收POST方法上传的XML

本文介绍了一种基于HTTP协议和XML的数据交换方式,通过IIS和ASP.NET实现了服务器端处理,客户端则使用HttpWebRequest和HttpWebResponse进行POST请求,演示了完整的通信流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天正在研究HTTP协议 ,想用HTTP加XML设计一通讯协议,就像SOAP和XML-RPC,所以通讯的两端都要实现HTTP协议,为了简便,想用IIS实现,使用ASP.NET开发的WEB应用程序处理通讯过程,就想使用HTTP协议中的POST方法传递信息,查了一些资料,做了一个测试程序。

在服务器端,设计一个页面处理程序,页面default.aspx内容为:

因为通讯内容为XML所以把HTML的相应元素全删了,后台代码如下:

using System;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.IO;

using System.Text;

namespace PostDataServer
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Encoding coding = Encoding.Default;
try{
coding = Encoding.GetEncoding(Request.Headers["Content-Encoding"]);
}
catch{}
StreamReader rdr = new StreamReader(Request.InputStream, coding);
string line;
while ((line = rdr.ReadLine()) != null) {
sb.Append(line);
}
Response.ContentEncoding = coding; // according to request encoding
Response.Write(sb.ToString());
}
}
}

客户端,使用HttpWebRequest和HttpWebResponse处理

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.IO;

using System.Net.Sockets;

namespace SocketWebService
{
public partial class SocketClient : Form
{

public SocketClient()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try {
string message = "<?xml version=/"1.0/" encoding=/"utf-8/" ?>/r/n"
+ "<message>/r/n" <br> + " Hello from 客户端 via http/r/n" <br> + "</message>";

Encoding coding = Encoding.UTF8;
try {
coding = Encoding.GetEncoding("gb2312");
}
catch { }
byte[] data = coding.GetBytes(message);
Uri url = new Uri(txtUrl.Text);

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";

req.Headers.Add(HttpRequestHeader.ContentEncoding, coding.HeaderName);

req.ContentType = "text/xml";
req.ContentLength = data.Length;
Stream wtr = (req.GetRequestStream());
wtr.Write(data, 0, data.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader rdr = new StreamReader(res.GetResponseStream(), coding);
string line;
txtOuput.Text = "";
while ((line = rdr.ReadLine()) != null) {
txtOuput.Text += "/r/n" + line;
}
wtr.Close();
rdr.Close();
res.Close();
}
catch (Exception ee) {
MessageBox.Show(ee.Message);
return;
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值