这几天正在研究HTTP协议 ,想用HTTP加XML设计一通讯协议,就像SOAP和XML-RPC,所以通讯的两端都要实现HTTP协议,为了简便,想用IIS实现,使用ASP.NET开发的WEB应用程序处理通讯过程,就想使用HTTP协议中的POST方法传递信息,查了一些资料,做了一个测试程序。
在服务器端,设计一个页面处理程序,页面default.aspx内容为:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PostDataServer._Default" EnableViewState="false" ContentType="text/xml" %>
因为通讯内容为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 = "
/r/n"
+ "
/r/n"
+ " Hello from 客户端 via http/r/n"
+ "
";
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;
}
}
}
}