UTF-8页如何接收和使用以GB2312方式进行URL编码的中文数据
时间:2010-11-11 来源:顺德早茶
比如“汉”字:
以GB2312编码进行URLEncode后:%BA%BA
以UTF-8编码进行URLEncode后:%E6%B1%89
如果将以GB2312编码进行URLEncode后的数据%BA%BA直接通过URL传递给UTF-8编码的网页,并在网页中直接以Request.QueryString方式读取数据,就会有乱码问题。解决方法如下:
功能实现函数1 '说明:在UTF-8编码网页中读取以GB2312方式编码的URLEncode数据功能函数使用实例
2 '使用:URLDecode(GBToUTF8(QueryString("a")))
3
4 Function GBQueryString(ByVal sQueryName)
5 Dim iCodePage
6 iCodePage = Session.CodePage
7 Session.CodePage = 936
8 GBQueryString = Request.QueryString(sQueryName)
9 Session.CodePage = iCodePage
10 End Function
11
12 Function GBToUTF8(sInput)
13 Dim wChar, uChar, nAsc, sResult, i
14
15 '如果输入参数为空,则退出函数
16 If sInput = "" Then
17 GBToUTF8 = sInput
18 Exit Function
19 End If
20 '开始转换
21 For i = 1 To Len(sInput)
22 '利用mid函数分拆GB编码文字
23 wChar = Mid(sInput, i, 1)
24 '利用ascW函数返回每一个GB编码文字的Unicode字符代码
25 '注:asc函数返回的是ANSI 字符代码,注意区别
26 nAsc = AscW(wChar)
27 If nAsc < 0 Then nAsc = nAsc + 65536
28
29 If (nAsc And &HFF80) = 0 Then
30 sResult = sResult & wChar
31 Else
32 If (nAsc And &HF000) = 0 Then
33 uChar = "%" & Hex(((nAsc \ 2 ^ 6)) Or &HC0) & Hex(nAsc And &H3F Or &H80)
34 sResult = sResult & uChar
35 Else
36 'GB编码文字的Unicode字符代码在0800 - FFFF之间采用三字节模版
37 uChar = "%" & Hex((nAsc \ 2 ^ 12) Or &HE0) & "%" & Hex((nAsc \ 2 ^ 6) And &H3F Or &H80) & "%" & Hex(nAsc And &H3F Or &H80)
38 sResult = sResult & uChar
39 End If
40 End If
41 Next
42
43 GBToUTF8 = sResult
44 End Function
45
46 Function URLDecode(enStr)
47 Dim deStr, sSpecial, c, i, v
48 deStr = ""
49 sSpecial = "!""#$%&'()*+,.-_/:;<=>?@[\]^`{|}~%"
50 For i = 1 To Len(enStr)
51 c = Mid(enStr, i, 1)
52 If c = "%" Then
53 v = Eval("&h" + Mid(enStr, i + 1, 2))
54 If InStr(sSpecial, Chr(v)) > 0 Then
55 deStr = deStr & Chr(v)
56 i = i + 2
57 Else
58 v = Eval("&h" + Mid(enStr, i + 1, 2) + Mid(enStr, i + 4, 2))
59 deStr = deStr & Chr(v)
60 i = i + 5
61 End If
62 Else
63 If c = "+" Then
64 deStr = deStr & " "
65 Else
66 deStr = deStr & c
67 End If
68 End If
69 Next
70 URLDecode = deStr
71 End Function
1 Dim sTest
2
3 '取得URL传过来的Test的内容
4 sTest = URLDecode(GBToUTF8(QueryString("Test")))
5 '输出Test的内容到页面上
6 Response.Write(sTest)
相关阅读 更多 +