天天看點

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,如需轉載請自行聯系原作者 

繼續閱讀