第二种解决方案只是对 Base64 编码的字符串进行 URLEncode。我在这里使用公共编解码器进行编码。Java 代码:
public class CookieDecoder {
private static final Log log = LogFactory.getLog(CookieDecoder.class);
/**
* @param cookieValue The value of the cookie to decode
* @return Returns the decoded string
*/
public String decode(String cookieValue) {
if (cookieValue == null || "".equals(cookieValue)) {
return null;
}
if (log.isDebugEnabled()) {
log.debug("Decoding string: " + cookieValue);
}
URLCodec urlCodec = new URLCodec();
String b64Str;
try {
b64Str = urlCodec.decode(cookieValue);
}
catch (DecoderException e) {
log.error("Error decoding string: " + cookieValue);
return null;
}
Base64 base64 = new Base64();
byte[] encodedBytes = b64Str.getBytes();
byte[] decodedBytes = base64.decode(encodedBytes);
String result = new String(decodedBytes);
if (log.isDebugEnabled()) {
log.debug("Decoded string to: " + result);
}
return result;
}
}
但现在我也必须在 JavaScript 端对其进行解码......编码:
var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + escape(encodedValue) +
"; expires=" + this.expires.toGMTString() +
"; path=" + this.path;
解码:
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
var encodedValue = c.substring(nameEQ.length,c.length);
return this.base64.decode(unescape(encodedValue));
}
}
return null;