14

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();
                }


            }
        }

    }

I get:

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.

Spectric
  • 30,714
  • 6
  • 20
  • 43
Nishit Jain
  • 1,549
  • 8
  • 21
  • 33

2 Answers2

28

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");
// ...
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

this answer might be not relevant for this question but i get this error with JBoss EAP so if you are using JBoss EAP you should change EAP language in standalone.conf.bat

find this line

set "JAVA_OPTS=-Xms1G -Xmx1G -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=256m"

and add this parameter after -Xmx1G

-Duser.language=en