Web亂碼折騰夠嗆 小小妙招輕松搞定
Web數據提交有兩種方法:GET 和 POST。關于這兩種方法的介紹,請看這里:Http之Get/Post請求區別。我在這里要介紹的是如何在程序中獲取HTTPRequest數據,并成功解決編碼不同時所引起亂碼的問題。
現在我們開始,先看一段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>無標題文檔</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"/>
- <br />
- <br />
- <input type="submit" value="提交" />
- </form>
- </body>
- </html>
在這個HTML文件中,我們使用的編碼是GB2312,Form表單中包含name和age兩個數據。首先將method設置為GET方法:
- <form id="myForm" action="http://localhost:9000/WebForm1.aspx" method="GET">
另外我們再新建一個Web應用程序,并在本地新建一個站點,將端口設置為9000,添加一個頁面,名稱為WebForm1.aspx,也就是上面Form表單中的action所指向的地址http://localhost:9000/WebForm1.aspx
在點擊“提交”按鈕的時候,我們可以在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">
在點擊“提交”按鈕的時候,我們可以在WebForm1中獲取到網頁的參數,具體有如下幾種方式:
- Request["name"]
- Request.Params["name"]
- Request.Form["name"]
和***種問題相同,經過默認的UTF-8轉換,這里還會出現亂碼。這是第二種問題。
問題一的解決方法:
- 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()]);
- }
另外,對于***種方法,還可以直接將URL用GB2312解碼,這里不再貼出代碼。
有了這兩種方法,不管是怎樣的亂碼,都可以高枕無憂了。
原文鏈接:http://www.cnblogs.com/youring2/archive/2011/03/24/1993717.html
【編輯推薦】