【问题标题】:how to use HttpListener to receive HTTP Post which contain XML如何使用 HttpListener 接收包含 XML 的 HTTP Post
【发布时间】:2011-08-10 00:25:33
【问题描述】:
我正在开发一个项目,该项目将接收包含 XML 数据的 HTTP POST。我将设置 HttpListener 来接收 HTTP POST,然后用 ACK 响应。
我想知道是否有实现类似功能的示例? HttpListener 可以同时处理多少个请求?
我将有一个消息队列来存储来自客户端的请求。而且我必须设置一个测试客户端来将请求发送到 HttpListener 以进行测试。我应该设置 WebRequest 还是其他东西来测试 HttpListener?
【问题讨论】:
标签:
xml
http
post
httplistener
【解决方案1】:
您可以使用 HttpListener 来处理传入的 HTTP POST,您几乎可以按照您为侦听器找到的任何教程进行操作。这是我的做法(注意这是同步的,一次处理超过 1 个请求,您需要使用线程或至少使用异步方法。)
public void RunServer()
{
var prefix = "http://*:4333/";
HttpListener listener = new HttpListener();
listener.Prefixes.Add(prefix);
try
{
listener.Start();
}
catch (HttpListenerException hlex)
{
return;
}
while (listener.IsListening)
{
var context = listener.GetContext();
ProcessRequest(context);
}
listener.Close();
}
private void ProcessRequest(HttpListenerContext context)
{
// Get the data from the HTTP stream
var body = new StreamReader(context.Request.InputStream).ReadToEnd();
byte[] b = Encoding.UTF8.GetBytes("ACK");
context.Response.StatusCode = 200;
context.Response.KeepAlive = false;
context.Response.ContentLength64 = b.Length;
var output = context.Response.OutputStream;
output.Write(b, 0, b.Length);
context.Response.Close();
}
从请求中获取 XML 的主要部分是这一行:
var body = new StreamReader(context.Request.InputStream).ReadToEnd();
这将为您提供 HTTP 请求的正文,其中应包含您的 XML。您可以将其直接发送到任何可以从流中读取的 XML 库中,但是如果杂散的 HTTP 请求也被发送到您的服务器,请务必注意异常。