先把代碼放在這里,下面再詳細解說:
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Oracle.DataAccess.Client; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; namespace ConsoleApplication1 { class Program { static Object o = new object(); static void Main(string[] args) { HttpListener listerner = new HttpListener(); 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("服務器啟動成功......."); //線程池 int minThreadNum; int portThreadNum; int maxThreadNum; ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum); ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum); 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(new WaitCallback(TaskProc), ctx); } //listerner.Stop(); } Console.ReadKey(); } static void TaskProc(object o) { 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 = new System.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 = new StreamWriter(ctx.Response.OutputStream,Encoding.UTF8)) { writer.Write("處理結果,Hello world<br/>"); writer.Write("數據是userId={0},userName={1}", userId, userName); writer.Close(); ctx.Response.Close(); } } } }
1.可通過HttpUtility.UrlDecode對傳入的參數進行解碼,防止中文亂碼
2.StreamWriter必須使用UTF8格式,防止中文亂碼
3.微軟提供的HttpListener默認不能接收POST參數,所以需要自己去解析,上面已實現
4.界面可通過form的post方式直接提交數據