java.lang.IllegalArgumentException:控制Cookie值或属性中的字符 [英] java.lang.IllegalArgumentException: Control character in cookie value or attribute

查看:1853
本文介绍了java.lang.IllegalArgumentException:控制Cookie值或属性中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在cookie中设置unicode值,但它不接受这个并抛出异常。我检查了字符串的十六进制值,它是正确的,但在添加到一个cookie时抛出异常。

I am trying to set the unicode value inside the cookie but it doesn't accept this and throws Exception. I have checked the hexadecimal value of the string and it is correct but throws Exception while adding to a 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.

。我使用Tomcat 7和Java 7作为运行时环境。

when adding the cookie to response object. I am using Tomcat 7 and Java 7 as the runtime environment.

推荐答案

版本0的cookie值是允许的字符限制。它只允许网址安全的字符。这包括字母数字字符(az,AZ和0-9)和仅少数词汇字符,包括 - _ 。所有其他字符在版本0的Cookie中无效。

Version 0 cookie values are restrictive in allowed characters. It only allows URL-safe characters. This covers among others the alphanumeric characters (a-z, A-Z and 0-9) and only a few lexical characters, including -, _, ., ~ and %. All other characters are invalid in version 0 cookies.

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

Your best bet is to URL-encode those characters. This way every character which is not allowed in URLs will be percent-encoded in this form %xx which is valid as cookie value.

因此,创建cookie时,请执行以下操作:

So, when creating the cookie do:

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

阅读cookie时,执行:

And when reading the cookie, do:

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

这篇关于java.lang.IllegalArgumentException:控制Cookie值或属性中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆