作者:ludewig 链接:https://blog.csdn.net/lordwish/article/details/86615077
C#代码
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Text;namespace TestHttpListener{class Program{static void Main(string[] args){HttpListener listener = new HttpListener();listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;listener.Prefixes.Add("http://localhost:8899/");listener.Start();Console.WriteLine("HttpListener");listener.BeginGetContext(ListenerHandle, listener);Console.ReadKey();listener.Stop();listener.Close();}static int i = 0;private static void ListenerHandle(IAsyncResult result){HttpListener listener = result.AsyncState as HttpListener;if (listener == null){return;}if (listener.IsListening){HttpListenerContext context = listener.EndGetContext(result);//解析Request请求HttpListenerRequest request = context.Request;switch (request.HttpMethod){case "POST":break;case "GET":foreach (var item in request.QueryString.AllKeys){Console.WriteLine($"Key={item},Value={request.QueryString[item]}");}//构造Response响应HttpListenerResponse response = context.Response;response.StatusCode = 200;response.ContentType = "application/json;charset=UTF-8";response.ContentEncoding = Encoding.UTF8;response.AppendHeader("Content-Type", "application/json;charset=UTF-8");StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8);writer.Write("TestHttpListener " + i++);writer.Close();response.Close();break;}listener.BeginGetContext(ListenerHandle, result.AsyncState);}}}}
注1
localhost可以改成本机IP地址
注2
启动失败显示拒绝访问时,使用管理员身份运行
注3
在另一台机器打开访问没反应时,检查双方的防火墙进行开放端口,或者直接关闭(不推荐)
注4
参数的获取
浏览器输入 http://localhost:8899/?id=4567
控制台显示
