天天看点

Web乱码解决方法

最近被乱码折腾的够呛,现在工作告一段落,出来总结一下Web中传递数据乱码的情况,希望同样被乱码困扰的朋友能够安心入睡!

现在我们开始,先看一段HTML代码:

Web乱码解决方法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>无标题文档</title>

</head>

<body>

<form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="post">

名称:<input tyep="text" name="name" width="200px" value="独钓寒江"/>

<br />

年龄:<input tyep="text" name="age" width="200px" value="24"/>

<input type="submit" value="提交" />

</form>

</body>

</html>

Web乱码解决方法

在这个HTML文件中,我们使用的编码是GB2312,Form表单中包含name和age两个数据。首先将method设置为GET方法:

<form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="GET">

在点击“提交”按钮的时候,我们可以在WebForm1中获取到网页的参数,具体有如下几种方式:

Request["name"]

Request.Params["name"]

Request.QueryString["name"]

这三种方法得到的字符串都是经过默认编码转换的,因为我们使用vs建立项目时编码默认为UTF-8,所以这时便会出现乱码。这是第一种问题,稍候我们将解决这个问题。

接下来将method设置为POST方法:

<form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="POST">

Request.Form["name"]

和第一种问题相同,经过默认的UTF-8转换,这里还会出现乱码。这是第二种问题。

问题一的解决方法:

Web乱码解决方法

StringBuilder sb = new StringBuilder();

IServiceProvider provider = (IServiceProvider)HttpContext.Current;

HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

byte[] bs = worker.GetQueryStringRawBytes();

String queryString = Encoding.GetEncoding("GB2312").GetString(bs);

NameValueCollection querys = HttpUtility.ParseQueryString(queryString, Encoding.GetEncoding("GB2312"));

foreach (var item in querys.Keys)

{

sb.AppendFormat("{0}:{1}<br />", item.ToString(), querys[item.ToString()]);

}

Web乱码解决方法

问题二的解决方法:

Web乱码解决方法

// 获取到InputStream

System.IO.Stream str = Request.InputStream;

Int32 strLen, strRead;

strLen = Convert.ToInt32(str.Length);

byte[] strArr = new byte[strLen];

strRead = str.Read(strArr, 0, strLen);

string queryString = HttpUtility.UrlDecode(strArr, System.Text.Encoding.GetEncoding("GB2312"));

Web乱码解决方法

另外,对于第一种方法,还可以直接将URL用GB2312解码,这里不再贴出代码。

有了这两种方法,不管是怎样的乱码,都可以高枕无忧了。

本文转自齐师傅博客园博客,原文链接:http://www.cnblogs.com/youring2/archive/2011/03/24/1993717.html,如需转载请自行联系原作者 

继续阅读