我已经使用http侦听器设置了一个Web服务器。它用来显示一个html文件。该html文件创建了一个我希望应用程序获得的请求。这里是小提琴手请求的截图: This is the only request that needs to be captured使用http侦听器获取端口上的Web流量
这是我的尝试:
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
Console.Write(ctx.Response.OutputStream);
该代码总是返回“System.Net.HttpResponseStream”每一个请求是在服务器上进行的时间。我想看看它是什么回来,但作为一个字符串。
这里是我的Web服务器代码:
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(IReadOnlyCollection<string> prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
{
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
}
// URI prefixes are required eg: "http://localhost:8080/test/"
if (prefixes == null || prefixes.Count == 0)
{
throw new ArgumentException("URI prefixes are required");
}
if (method == null)
{
throw new ArgumentException("responder method required");
}
foreach (var s in prefixes)
{
_listener.Prefixes.Add(s);
}
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method)
{
}
public void Run()
{
ThreadPool.QueueUserWorkItem(o =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem(c =>
{
var ctx = c as HttpListenerContext;
try
{
if (ctx == null)
{
return;
}
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
// ignored
}
finally
{
// always close the stream
if (ctx != null)
{
ctx.Response.OutputStream.Close();
}
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
// ignored
}
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}
可以试试这个Console.Write(buf); –
[请勿将标记置于问题标题中](https://stackoverflow.com/help/tagging) – Liam