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 => {
    })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM