java.lang.IllegalArgumentException:控制cookie值或属性中的字符

Nis*_*ain 13 cookies servlets

我试图在cookie中设置unicode值,但它不接受这个并抛出异常.我检查了字符串的十六进制值,它是正确的,但在添加到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();
                }


            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

我明白了:

java.lang.IllegalArgumentException: Control character in cookie value or attribute.
Run Code Online (Sandbox Code Playgroud)

将cookie添加到响应对象时.我使用Tomcat 7和Java 7作为运行时环境.

Bal*_*usC 23

版本0 cookie值在允许的字符中是限制性的.它只允许URL安全字符.这包括在其他的字母数字字符(az,AZ和0-9),只有少数词汇字符,包括-,_,.,~%.版本0 cookie中的所有其他字符均无效.

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

所以,在创建cookie时:

Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
// ...
Run Code Online (Sandbox Code Playgroud)

在阅读cookie时,请执行以下操作:

String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
// ...
Run Code Online (Sandbox Code Playgroud)