这几天,重温自己写的web java聊天室,其实有个问题就是浏览器post的中文显示为问号,花了点时间终于把它解决了,解决办法是把网页默认编码和java源文件(elipse需设为utf8文本编码)都统一使用utf8编码,然后再在post的时候直接处理百分号后面的16进制字符串,代码见下:
private String decodePercent(String str) throws InterruptedException {
try {
StringBuffer sb = new StringBuffer();
int j = 0;
byte[] theByte = new byte[9];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
System.out.println("sub =" + str.substring(i + 1, i + 3));
j++;
try {
System.out.println("sub str1="+ str.substring(i + 1, i + 3));
theByte[(j - 1) % 3] = Integer.decode("0X" + str.substring(i + 1, i + 3)).byteValue();
if(j%3==0){
System.out.println("sb=" + new String(theByte, 0,theByte.length, "UTF-8"));
sb.append(new String(theByte, 0, theByte.length,"UTF-8"));
}
} catch (Exception Ue) {
Ue.printStackTrace();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
return new String(sb.toString());
} catch (Exception e) {
System.out.println("BAD REQUEST: Bad percent-encoding.");
return null;
}
}
其中关键代码是,theByte[(j - 1) % 3] = Integer.decode("0X" + str.substring(i + 1, i + 3)).byteValue();和new String(theByte, 0, theByte.length,"UTF-8")
也就是把百分号之间的中文16进制编码放到一个字节数组里然后按utf8处理。
阅读(1987) | 评论(0) | 转发(0) |