2012-02-02 21 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

相關問題