关于c#:C-解决httplistener-querystring-中文乱码返回json中文格式乱码

61次阅读

共计 840 个字符,预计需要花费 3 分钟才能阅读完成。

解决 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();}
}

转载于:链接

正文完
 0