2012-02-02 55 views
13

我试图设置cookie内的unicode值,但它不接受这个并抛出异常。我检查了字符串的十六进制值,它是正确的,但在添加到cookie时抛出异常。java.lang.IllegalArgumentException:Cookie值或属性中的控制字符

private void fnSetCookieValues(HttpServletRequest request,HttpServletResponse response) 
    { 

     Cookie[] cookies=request.getCookies(); 
     for (int i = 0; i < cookies.length; i++) { 

      System.out.println(""+cookies.length+"Name"+cookies[i].getName()); 

      if(cookies[i].getName().equals("DNString")) 
      { 
       System.out.println("Inside if:: "+cookies[i].getValue()+""+cookies.length); 
       try { 

        String strValue; 
        strValue = new String(request.getParameter("txtIIDN").getBytes("8859_1"),"UTF8"); 
        System.out.println("Cookie Value To be stored"+strValue); 
        for (int j = 0; j < strValue.length(); j++) { 

         System.out.println("Code Point"+Integer.toHexString(strValue.codePointAt(j))); 

        } 


        Cookie ck = new Cookie("DNString",strValue); 
        response.addCookie(ck); 

       } catch (UnsupportedEncodingException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 


      } 
     } 

    } 

我得到:

java.lang.IllegalArgumentException: Control character in cookie value or attribute. 

添加cookie来响应物体时。我使用Tomcat 7和Java 7作为运行时环境。

回答

22

版本0 cookie值限制允许的字符数。它只允许URL安全的字符。这包括字母数字字符(a-z,A-Z和0-9)以及仅包括几个词汇字符,其中包括-,_,.,~%。所有其他字符在版本0 cookie中无效。

最好的办法是对这些字符进行URL编码。这样,URL中不允许的每个字符都将以这种形式进行百分比编码,其格式为%xx,这是有效的cookie值。

因此,在创建cookie时做到:

Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8")); 
// ... 

和读取cookie时,这样做:

String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); 
// ... 
+0

感谢它的作品! – 2012-02-03 05:14:11

+0

不客气。 – BalusC 2012-02-03 05:14:32