Chinaunix首页 | 论坛 | 博客
  • 博客访问: 72506
  • 博文数量: 8
  • 博客积分: 474
  • 博客等级: 下士
  • 技术积分: 100
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-24 12:00
文章分类

全部博文(8)

文章存档

2014年(2)

2012年(2)

2011年(3)

2010年(1)

分类: Java

2011-07-26 20:34:36

这几天,重温自己写的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处理。
 
阅读(1918) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~