Web亂碼折騰夠嗆 小小妙招輕松搞定
Web數(shù)據(jù)提交有兩種方法:GET 和 POST。關(guān)于這兩種方法的介紹,請(qǐng)看這里:Http之Get/Post請(qǐng)求區(qū)別。我在這里要介紹的是如何在程序中獲取HTTPRequest數(shù)據(jù),并成功解決編碼不同時(shí)所引起亂碼的問題。
現(xiàn)在我們開始,先看一段HTML代碼:
- <!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>無標(biāo)題文檔</title>
- </head>
- <body>
- <form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="post">
- 名稱:<input tyep="text" name="name" width="200px" value="獨(dú)釣寒江"/>
- <br />
- 年齡:<input tyep="text" name="age" width="200px" value="24"/>
- <br />
- <br />
- <input type="submit" value="提交" />
- </form>
- </body>
- </html>
在這個(gè)HTML文件中,我們使用的編碼是GB2312,F(xiàn)orm表單中包含name和age兩個(gè)數(shù)據(jù)。首先將method設(shè)置為GET方法:
- <form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="GET">
另外我們?cè)傩陆ㄒ粋€(gè)Web應(yīng)用程序,并在本地新建一個(gè)站點(diǎn),將端口設(shè)置為9000,添加一個(gè)頁面,名稱為WebForm1.aspx,也就是上面Form表單中的action所指向的地址http://localhost:9000/WebForm1.aspx
在點(diǎn)擊“提交”按鈕的時(shí)候,我們可以在WebForm1中獲取到網(wǎng)頁的參數(shù),具體有如下幾種方式:
- Request["name"]
- Request.Params["name"]
- Request.QueryString["name"]
這三種方法得到的字符串都是經(jīng)過默認(rèn)編碼轉(zhuǎn)換的,因?yàn)槲覀兪褂胿s建立項(xiàng)目時(shí)編碼默認(rèn)為UTF-8,所以這時(shí)便會(huì)出現(xiàn)亂碼。這是***種問題,稍候我們將解決這個(gè)問題。
接下來將method設(shè)置為POST方法:
- <form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="POST">
在點(diǎn)擊“提交”按鈕的時(shí)候,我們可以在WebForm1中獲取到網(wǎng)頁的參數(shù),具體有如下幾種方式:
- Request["name"]
- Request.Params["name"]
- Request.Form["name"]
和***種問題相同,經(jīng)過默認(rèn)的UTF-8轉(zhuǎn)換,這里還會(huì)出現(xiàn)亂碼。這是第二種問題。
問題一的解決方法:
- 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()]);
- }
問題二的解決方法:
- // 獲取到InputStream
- System.IO.Stream str = Request.InputStream;
- Int32 strLen, strRead;
- strLen = Convert.ToInt32(str.Length);
- byte[] strArr = new byte[strLen];
- strstrRead = str.Read(strArr, 0, strLen);
- string queryString = HttpUtility.UrlDecode(strArr, System.Text.Encoding.GetEncoding("GB2312"));
- NameValueCollection querys = HttpUtility.ParseQueryString(queryString, Encoding.GetEncoding("GB2312"));
- foreach (var item in querys.Keys)
- {
- sb.AppendFormat("{0}:{1}<br />", item.ToString(), querys[item.ToString()]);
- }
另外,對(duì)于***種方法,還可以直接將URL用GB2312解碼,這里不再貼出代碼。
有了這兩種方法,不管是怎樣的亂碼,都可以高枕無憂了。
原文鏈接:http://www.cnblogs.com/youring2/archive/2011/03/24/1993717.html
【編輯推薦】