您的位置:首页 > 理论基础 > 计算机网络

彻底解决网络传输过程中出现的中文乱码问题

2009-06-16 00:37 766 查看
很奇怪的事情,有页面 index.asp 为UTF-8页面,用Ajax发送参数
"name="+escape("朝歌")+"&id=23" 到页面 resource.asp (gb2312)后,返回
vbsEscape(“中文”)后,AJAX在unescape后居然能读出汉字,这个太神奇了,最后才知道原来escape和unescape这两个算法是互为解密和加密的两个程序,不受编码影响(也就是不管在UTF-8还是gb2312中,其结果是互相唯一的),因为很多时候编码出现故障都是因为中文编码而出现的,现在由于此两个程序把中文编成普通的字符,所以传输过程中不会乱,发出去的是普通字符,根据算法逆运算就可以得出真正的字符.

现在贴出ASP和JAVA的escape和unescape函数
vbscript
Function Escape(str)
dim i,s,c,a
s=""
For i=1 to Len(str)
c=Mid(str,i,1)
a=ASCW(c)
If (a>=48 and a<=57) or (a>=65 and a<=90) or (a>=97 and a<=122) Then
s = s & c
ElseIf InStr("@*_+-./",c)>0 Then
s = s & c
ElseIf a>0 and a<16 Then
s = s & "%0" & Hex(a)
ElseIf a>=16 and a<256 Then
s = s & "%" & Hex(a)
Else
s = s & "%u" & Hex(a)
End If
Next
vbsEscape = s
End Function

Function UnEscape(str)
dim i,s,c
s=""
For i=1 to Len(str)
c=Mid(str,i,1)
If Mid(str,i,2)="%u" and i<=Len(str)-5 Then
If IsNumeric("&H" & Mid(str,i+2,4)) Then
s = s & CHRW(CInt("&H" & Mid(str,i+2,4)))
i = i+5
Else
s = s & c
End If
ElseIf c="%" and i<=Len(str)-2 Then
If IsNumeric("&H" & Mid(str,i+1,2)) Then
s = s & CHRW(CInt("&H" & Mid(str,i+1,2)))
i = i+2
Else
s = s & c
End If
Else
s = s & c
End If
Next
vbsUnEscape = s
End Function


java
public String escape(String src) {
int i;
char j;
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length() * 6);
for (i = 0; i < src.length(); i++) {
j = src.charAt(i);
if (Character.isDigit(j) || Character.isLowerCase(j)
|| Character.isUpperCase(j))
tmp.append(j);
else if (j < 256) {
tmp.append("%");
if (j < 16)
tmp.append("0");
tmp.append(Integer.toString(j, 16));
} else {
tmp.append("%u");
tmp.append(Integer.toString(j, 16));
}
}
return tmp.toString();
}

public String unescape(String src) {
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos = 0, pos = 0;
char ch;
while (lastPos < src.length()) {
pos = src.indexOf("%", lastPos);
if (pos == lastPos) {
if (src.charAt(pos + 1) == 'u') {
ch = (char) Integer.parseInt(src
.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
ch = (char) Integer.parseInt(src
.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else {
if (pos == -1) {
tmp.append(src.substring(lastPos));
lastPos = src.length();
} else {
tmp.append(src.substring(lastPos, pos));
lastPos = pos;
}
}
}
return tmp.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: