c#搭建一个http服务器代码
代码语言:c#
所属分类:其他
代码描述:c#搭建一个http服务器代码,可以处理post和get数据
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
using System; using System.IO; using System.Net; using System.Text; class Program { static void Main(string[] args) { string url = "http://localhost:8080/"; HttpListener listener = new HttpListener(); listener.Prefixes.Add(url); Console.WriteLine($"Listening on {url}"); listener.Start(); while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; Console.WriteLine($"Request received: {request.HttpMethod} {request.Url}"); // 处理 POST 数据 if (request.HttpMethod == "POST") { StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding); string requestBody = reader.ReadToEnd(); Console.WriteLine($"POST data received: {requestBody}"); // 这里可以根据需要处理 POST 数据,比如解析 JSON 或表单数据 } // 处理 GET 数据 string query = request.Url.Query; Console.WriteLine($"Query string: {query}"); // 处理 Cookie string cookiesHeader = request.Headers["Cookie"]; Console.WriteLine($"Cookies: {cookiesHeader}"); .........完整代码请登录后点击上方下载按钮下载查看
网友评论0