在Tomcat8.0中,遇到了Cookie中value值中文乱码的问题
写了一个通用的方法,用于查询value值为中文,指定key值的cookie
public static Cookie add(String name,String value) { try { if(name==null||value==null){ return null; }else { //利用base64编码 BASE64Encoder base64Encoder=new BASE64Encoder(); String encode = base64Encoder.encode(value.getBytes("UTF-8")); Cookie cookie =new Cookie(name,encode); return cookie; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
public static Cookie getChineseCookie(String name,Cookie[] cookies) { try { if (name==null || cookies==null || cookies.length==0){ return null; }else { for (Cookie cookie:cookies){ if(name.equals(cookie.getName())){ //利用了BASE64解码 BASE64Decoder base64Decoder=new BASE64Decoder(); byte[] bytes = base64Decoder.decodeBuffer(cookie.getValue()); String value =new String(bytes,"UTF-8"); Cookie cookie1 =new Cookie(cookie.getName(),value); return cookie1; } } } } catch (Exception e) { e.printStackTrace(); } return null; }