winform 监听http_C# 监听HTTP请求

usingNewtonsoft.Json;usingNewtonsoft.Json.Linq;usingOracle.DataAccess.Client;usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;usingSystem.Web;namespaceConsoleApplication1

{classProgram

{static Object o = new object();static void Main(string[] args)

{

HttpListener listerner= newHttpListener();while (true)

{try{

listerner.AuthenticationSchemes= AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问

listerner.Prefixes.Add("http://127.0.0.1:1500/Service/");

listerner.Start();

}catch(Exception ex)

{

Console.WriteLine("服务启动失败...");break;

}

Console.WriteLine("服务器启动成功.......");//线程池

intminThreadNum;intportThreadNum;intmaxThreadNum;

ThreadPool.GetMaxThreads(out maxThreadNum, outportThreadNum);

ThreadPool.GetMinThreads(out minThreadNum, outportThreadNum);

Console.WriteLine("最大线程数:{0}", maxThreadNum);

Console.WriteLine("最小空闲线程数:{0}", minThreadNum);//ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);

Console.WriteLine("\n\n等待客户连接中。。。。");while (true)

{//等待请求连接//没有请求则GetContext处于阻塞状态

HttpListenerContext ctx =listerner.GetContext();

ThreadPool.QueueUserWorkItem(newWaitCallback(TaskProc), ctx);

}//listerner.Stop();

}

Console.ReadKey();

}static void TaskProc(objecto)

{

HttpListenerContext ctx=(HttpListenerContext)o;

ctx.Response.StatusCode= 200;//设置返回给客服端http状态代码//接收Get参数

string type = ctx.Request.QueryString["type"];string userId = ctx.Request.QueryString["userId"];string password = ctx.Request.QueryString["password"];string filename =Path.GetFileName(ctx.Request.RawUrl);string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码//进行处理

Console.WriteLine("收到数据:" +userName);//接收POST参数

Stream stream =ctx.Request.InputStream;

System.IO.StreamReader reader= newSystem.IO.StreamReader(stream, Encoding.UTF8);

String body=reader.ReadToEnd();

Console.WriteLine("收到POST数据:" +HttpUtility.UrlDecode(body));

Console.WriteLine("解析:" + HttpUtility.ParseQueryString(body).Get("userName"));//使用Writer输出http响应代码,UTF8格式

using (StreamWriter writer = newStreamWriter(ctx.Response.OutputStream,Encoding.UTF8))

{

writer.Write("处理结果,Hello world
");

writer.Write("数据是userId={0},userName={1}", userId, userName);

writer.Close();

ctx.Response.Close();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值