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.
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");
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With