现在的位置: 首页 > 综合 > 正文

Control character in cookie value, consider BASE64 encoding your value

2013年05月15日 ⁄ 综合 ⁄ 共 1551字 ⁄ 字号 评论关闭

项目当中用到cookie保存中文,但是会报如下错误:

Control character in cookie value, consider BASE64 encoding your value

 

大概意思是保存到cookie当中的值存在控制字符,无法保存。但实际上数据是不存在这种问题的。再看后面的那句话,好像是将要保存的值进行了base64编码,可能是因为中文在编码时出现乱码导致一些控制字符的出现。

 

解决方案:将要保存的值进行URLEncoder.encode(value,"utf-8")编码。

在提取时,同样进行解码:

 

Java代码 复制代码
  1. /**  
  2.     * 添加一个cookie值  
  3.     * @param name 名称  
  4.     * @param value 值  
  5.     * @param time  cookie的有效期  
  6.     * @param response 保存cookie的对象  
  7.     */  
  8.     public static void setCookie(String name, String value, Integer time,HttpServletResponse response) {   
  9.        try {   
  10.            //关键点   
  11.            value = URLEncoder.encode(value,"UTF-8");  
  12.   
  13.        } catch (UnsupportedEncodingException e) { }   
  14.        Cookie cookie = new Cookie(name, value);   
  15.        cookie.setPath("/");   
  16.        cookie.setMaxAge(time);   
  17.        response.addCookie(cookie);   
  18.    }   
  19.   
  20.    /**  
  21.     * 根据name值,从cookie当中取值  
  22.     *  
  23.     * @param name    要获取的name  
  24.     * @param request cookie存在的对象  
  25.     * @return 与name对应的cookie值  
  26.     */  
  27.    public static String getCookie(String name, HttpServletRequest request) {   
  28.        Cookie[] cs = request.getCookies();   
  29.        String value = "";   
  30.        if (cs != null) {   
  31.            for (Cookie c : cs) {   
  32.                if (name.equals(c.getName())) {   
  33.                    try {   
  34.   
  35.                   //关键点     
  36.                     value = URLDecoder.decode(c.getValue(),"UTF-8");  
  37.   
  38.                    } catch (UnsupportedEncodingException e) {   
  39.                    }   
  40.                    return value;   
  41.                }   
  42.            }   
  43.        }   
  44.        return value;   
  45.   
  46.    }  

转自:http://amcucn.javaeye.com/blog/403857

抱歉!评论已关闭.