C# 解決httplistener querystring 中文亂碼、返回json中文格式亂碼


解決httplistener querystring 中文亂碼方案:

在請求到達時候,獲取Request.Url,返回get請求參數 鍵值對

    public class RequestHelper
    {
        public static Dictionary<string, string> EncodeQueryString(Uri uri)
        {
            var ret = new Dictionary<string, string>();
            var q = uri.Query;
            if (q.Length > 0)
            {
                foreach (var p in q.Substring(1).Split('&'))
                {
                    var s = p.Split(new char[] { '=' }, 2);
                    ret.Add(HttpUtility.UrlDecode(s[0]), HttpUtility.UrlDecode(s[1]));
                }
            }
            return ret;
        }
    }

解決返回json中文格式亂碼:

對中午json字符串進行編碼 HttpUtility.UrlDecode(“中文”);

  public class ResponseHelper
    {
        public static void Respose(HttpListenerResponse response, string jsonStr = "")
        {
            byte[] buffer = Encoding.UTF8.GetBytes(jsonStr);
            response.ContentLength64 = buffer.Length;
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.StatusCode = 200;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            //關閉輸出流,釋放相應資源
            output.Close();
            response.Close();
        }
    }

轉載於:鏈接


免責聲明!

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



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