将httpWebRequest发布到HttpListener

时间:2017-05-23 17:33:14

标签: c# httpwebrequest httplistener

我开始实现一个基本的C#服务器,它将处理POST和GET。

我有以下内容:

private static HttpListener listener;

private static void CreateListener()
{
    listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:1234/");
    listener.Start();
    listener.BeginGetContext(Process, listener);
    Console.WriteLine("Listening...");
}
private static void Process(IAsyncResult result)
{
    HttpListenerContext context = listener.EndGetContext(result);
    listener.BeginGetContext(Process, listener);
    Console.WriteLine(context);
    Console.ReadLine();
}

尝试使用基本的httpWebRequest

进行测试
private static void Post(string webAddress)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddress);
    httpWebRequest.ContentType = "application/json; charset=utf-8";
    httpWebRequest.Method = "POST";
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize("Some POSTed Data");
        streamWriter.Write(json);
        streamWriter.Flush();
    }
}
public static void Main(string[] args)
{
    CreateListener();
    Post("http://localhost:1234/");
    Console.WriteLine("Got here!!");
    Console.ReadLine();
}

但它似乎没有触发Process功能。那是为什么?

1 个答案:

答案 0 :(得分:1)

您必须致电httpWebRequest.GetResponse()向服务器发送请求并获得回复。

您可以在MSDN

中找到相关信息