c# winform httplistener监听get和Post请求并处理参数解决中文乱码
主要问题:后台接受的get请求参数是中文乱码,我用了很多方法转成汉字,但是超过三位最后一位就是乱码,比如 黄河远上白云? 最后发现解析他的url可以正常获得参数,感谢以前的前端面试题。Post请求json解析是没问题的,未出现乱码现象。以下为 winform 代码
using Newtonsoft.Json; using System.Net; using System.IO; private void Form1_Load(object sender, EventArgs e) { startHttpListen(); Control.CheckForIllegalCrossThreadCalls = false; } public void startHttpListen() { try { text_info.Text = "监听状态:正在启动"; listener.Prefixes.Add(listenUrl); //添加需要监听的url范围 listener.Start(); //开始监听端口,接收客户端请求; listener.BeginGetContext(ListenerHandle, listener); text_info.Text = "监听状态:已启动"; } catch { text_info.Text = "监听状态:监听失败"; } } /// <summary> /// 监听回调函数 /// </summary> private void ListenerHandle(IAsyncResult result) { try { if (listener.IsListening) { listener.BeginGetContext(ListenerHandle, result); HttpListenerContext context = listener.EndGetContext(result); HttpListenerResponse response = context.Response; HttpListenerRequest request = context.Request; context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件 context.Response.AppendHeader("Access-Control-Allow-Credentials", "true"); //后台跨域请求 response.StatusCode = 200; response.ContentType = "application/json;charset=UTF-8"; context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息 context.Response.AddHeader("Content-type", "application/x-www-form-urlencoded");//添加响应头信息 response.ContentEncoding = Encoding.UTF8; //解析Request请求 string content = ""; switch (request.HttpMethod) { case "POST": { // json字符串 Stream stream = request.InputStream; StreamReader reader = new StreamReader(stream, Encoding.UTF8); content = reader.ReadToEnd(); // Console.WriteLine(content); Worker worker = JsonConvert.DeserializeObject<Worker>(content); } break; case "GET": { // 没解决乱码问题,用url进行解析正常 string url = request.Url.ToString(); string[] pars = url.Split('?'); content = ""; if (pars.Length == 0) { return; } string canshus = pars[1]; if (canshus.Length > 0) { string[] canshu = canshus.Split('&'); foreach (string i in canshu) { string[] messages = i.Split('='); content += "参数为:" + messages[0] + " 值为:" + messages[1]; } } } break; } text_receive.Text += content; string responseString = "<HTML><BODY>" + content + "</BODY></HTML>"; byte[] buffers = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffers.Length; System.IO.Stream output = response.OutputStream; output.Write(buffers, 0, buffers.Length); // You must close the output stream. output.Close(); } } catch (Exception ex) { text_receive.Text += ex.Message; } } public class Worker { public int scoreFlag { get; set; } public int uid { get; set; } }
前端请求代码
const geturl="http://localhost:8888?name=黄河远上白云间"; const getIpUrl="http://192.168.110.241:8888?name=黄河远上白云间" axios.get(getIpUrl).then(res=>{ console.log(res) }).catch(err=>{ console.log(err) }); const data = { name: '黄山', id: '01' } const url = "http://192.168.110.241:8888" fetch( url, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', }, body: JSON.stringify(data) } ).then(res => { console.log(res); }).catch(err => { })