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

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.

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


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.

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.

So, when creating the cookie do:

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

And when reading the cookie, do:

String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
// ...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值