把UTF-8编码转换为GB2312编码(转csdn)

不同编码的页面、脚本之间互相引用,就会产生乱码的问题,解决方法就是统一成一种编码。
asp.net 中,如果要修改输出页面的编码,可以通过修改web.config中以下配置信息
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

以上只是修改整体的默认编码,如果只有某个页的编码需要修改,ASP.net 中则可以简单的使用下面代码:

Encoding gb2312 = Encoding.GetEncoding("gb2312");
Response.ContentEncoding
= gb2312;

在非ASP.net 应用中,可能你读到的数据是UTF-8编码,但是你要转换为GB2312编码,则可以参考以下代码:

 

string utfinfo = "document.write(\"alert('aa你好么??');\");";
string gb2312info = string.Empty;

Encoding utf8
= Encoding.UTF8;
Encoding gb2312
= Encoding.GetEncoding("gb2312");

// Convert the string into a byte[]. byte[] unicodeBytes = utf8.GetBytes(utfinfo);
// Perform the conversion from one encoding to the other. byte[] asciiBytes = Encoding.Convert(utf8, gb2312, unicodeBytes);

// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars. char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
gb2312.GetChars(asciiBytes,
0, asciiBytes.Length, asciiChars, 0);
gb2312info
= new string(asciiChars);

---------------------------------------------------------------------------------------------
在用ASP.NET写网上支付的接口程序时,遇到一个奇怪问题,通过表单提交过去的中文全是乱码,英文正常。而用asp程序进行测试,可以正常提交中文,asp页面中有这样的HTML代码:
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
可是将这个代码加入到ASP.NET页面中,依然解决不了问题。分析了一下,问题应该是编码引起的,对方的程序只能处理GB2312编码的页面提交过来的
中文数据。难道加了上面的代码,ASP.NET却不是以GB2312编码显示的?打开该页面,查看一下浏览器的编码,原来是UTF-8,原因找到,怎么解
决呢?看来,ASP.NET不理睬上面的代码,自己向浏览器发送编码信息,那我设置一下Response.ContentEncoding试试,在
Page_Load中加上如下代码:
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

-------------------------------------------------------------------------------------------

使asp.net的UrlEncode对应ASP的urlencode

论坛的用户名密码验证,那个验证程序是以前asp做的,接受用户名和密码两个参数,验证成功后输出xml格式的用户详细信
息。这之中发现一个问题,中文用户名经过asp.net的Server.UrlEncode
之后是4字节编码(UTF8),而asp的urlencode却是用的系统默认编码,2字节。开始想当然的用
Encoding.Convert转换一下,可惜试验几次都失败。
巧的是,本想看一下HttpServerUtility的UrlEncode有没有什么说明,结果马虎之下点上了 HttpUtility,发现里面也有一个UrlEncode,其中有一个重载
public static string UrlEncode(
   
string str,
   Encoding e
);
试一下 HttpUtility.UrlEncode (name, Encoding.Default).ToUpper();
OK! 跟asp的结果一样。
----------------------------------------------------------------------------

posted @ 2005-11-22 15:25  lanjue  阅读(926)  评论(0)    收藏  举报