我的应用需要从数据库中/从/从数据库中保存和还原HttpCookie(S(。因此,我尝试通过以下代码将httpcookie对象编码/解码为字符串。结果在某些情况下是错误消息:最后一个单元没有足够的有效位。
是的,我阅读了有关错误的帖子,但这是关于Reading-a-a-buffer&转换 - 缓冲器。这是不同的,因为流读数为1 go !
在某些情况下,此代码给出了上述错误消息。我该如何解决?
public class SerializableHttpCookie implements Serializable {
private static final long serialVersionUID = 6374381323722046732L;
private transient HttpCookie cookie;
private Field fieldHttpOnly; // needed for a workaround
...
public String encode2(HttpCookie cookie) {
this.cookie = cookie;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(this);
} catch (IOException e) {
logger.error( "IOException in encodeCookie", e);
return null;
}
return Base64.getUrlEncoder().encodeToString( os.toByteArray());
}
public HttpCookie decode2(String encodedCookie) {
byte[] bytes = Base64.getUrlDecoder().decode(encodedCookie);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( bytes);
HttpCookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).cookie;
} catch (IOException e) {
logger.error( "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
logger.error( "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
readObject和writeObject是:
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getCommentURL());
out.writeObject(cookie.getDomain());
out.writeLong(cookie.getMaxAge());
out.writeObject(cookie.getPath());
out.writeObject(cookie.getPortlist());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.getSecure());
out.writeBoolean(cookie.getDiscard());
out.writeBoolean(getHttpOnly());
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
cookie = new HttpCookie(name, value);
cookie.setComment((String) in.readObject());
cookie.setCommentURL((String) in.readObject());
cookie.setDomain((String) in.readObject());
cookie.setMaxAge(in.readLong());
cookie.setPath((String) in.readObject());
cookie.setPortlist((String) in.readObject());
cookie.setVersion(in.readInt());
cookie.setSecure(in.readBoolean());
cookie.setDiscard(in.readBoolean());
setHttpOnly(in.readBoolean());
}
我使用了不同的方法,例如以下导致错误(在计数中(。错误被标记为注释。
private String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString();
}
private byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16)); // ERROR: hexString.charAt(i+1) out of range
}
return data;
}
encodeandeserialize
这样做的另一种方法是调用答案中的代码。las,我在解码字符串时会遇到相同的错误。
new SerializableHttpCookie2().serializeAndEncode(cookie)));
和
HttpCookie cookie = new SerializableHttpCookie2().decodeAndDeserialize(encodedCookie);
使用Commons-Codec库:
public String serializeAndEncode(final HttpCookie cookie) throws IllegalAccessException, IllegalArgumentException {
final String serialized = this.serialize(cookie);
return new String( Hex.encodeHex(serialized.getBytes()));
}
和
public HttpCookie decodeAndDeserialize(final String string)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// final String decoded = this.decode(string);
String decoded;
try {
decoded = new String(Hex.decodeHex(string.toCharArray()));
} catch ( Exception e) {
return null;
}
return this.deserialize(decoded);
}
也许以下类解决您的问题
因为 HttpCookie
不实现 Serializable
,所以通过反射读取和写回值。
IM使用Java 12,在我的情况下,反射会触发警告,导致代码访问private final
字段。警告说:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by HttpCookieDeSerializer (file:...) to field java.net.HttpCookie.name
WARNING: Please consider reporting this to the maintainers of HttpCookieDeSerializer
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
类:
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.HttpCookie;
import java.util.Base64;
public class HttpCookieDeSerializer {
// TODO: need to be changed?
private final String fieldValueDelimiter = "===";
// TODO: need to be changed?
private final String fieldValuePairDelimiter = "###";
public HttpCookieDeSerializer() {
super();
}
public String decode(final String string) {
return new String(Base64.getUrlDecoder().decode(string));
}
public HttpCookie decodeAndDeserialize(final String string)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final String decoded = this.decode(string);
// TODO: remove sysout
System.out.println(decoded);
return this.deserialize(decoded);
}
public HttpCookie deserialize(final String decoded)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final String name = this.preGet(decoded, "name");
final String value = this.preGet(decoded, "value");
final HttpCookie cookie = new HttpCookie(name, value);
final String[] fieldsAndValues = decoded.split("(" + this.fieldValuePairDelimiter + ")");
for (final String fieldAndValue : fieldsAndValues) {
final String[] fieldAndValueSplitted = fieldAndValue.split("(" + this.fieldValueDelimiter + ")");
final Field field = HttpCookie.class.getDeclaredField(fieldAndValueSplitted[0]);
if (Modifier.isFinal(field.getModifiers())) {
// ???
// continue;
}
field.setAccessible(true);
final Class<?> type = field.getType();
if (String.class.equals(type)) {
field.set(cookie, this.convertNullStringToNullObject(fieldAndValueSplitted[1]));
} else if (Long.TYPE.equals(type)) {
field.setLong(cookie, Long.parseLong(fieldAndValueSplitted[1]));
} else if (Integer.TYPE.equals(type)) {
field.setInt(cookie, Integer.parseInt(fieldAndValueSplitted[1]));
} else if (Boolean.TYPE.equals(type)) {
field.setBoolean(cookie, Boolean.parseBoolean(fieldAndValueSplitted[1]));
}
}
return cookie;
}
public String encode(final String string) {
return Base64.getUrlEncoder().encodeToString(string.getBytes());
}
public String serialize(final HttpCookie cookie) throws IllegalAccessException, IllegalArgumentException {
final StringBuilder builder = new StringBuilder();
final Field[] fields = HttpCookie.class.getDeclaredFields();
boolean first = true;
for (final Field field : fields) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
if (!first) {
builder.append(this.fieldValuePairDelimiter);
}
builder.append(field.getName());
builder.append(this.fieldValueDelimiter);
final Class<?> type = field.getType();
field.setAccessible(true);
if (String.class.equals(type)) {
builder.append((String) field.get(cookie));
} else if (Long.TYPE.equals(type)) {
builder.append(Long.toString(field.getLong(cookie)));
} else if (Integer.TYPE.equals(type)) {
builder.append(Integer.toString(field.getInt(cookie)));
} else if (Boolean.TYPE.equals(type)) {
builder.append(Boolean.toString(field.getBoolean(cookie)));
}
first = false;
}
final String serialized = builder.toString();
return serialized;
}
public String serializeAndEncode(final HttpCookie cookie) throws IllegalAccessException, IllegalArgumentException {
final String serialized = this.serialize(cookie);
// TODO: remove sysout
System.out.println(serialized);
return this.encode(serialized);
}
private Object convertNullStringToNullObject(final String string) {
if ("null".equals(string)) {
return null;
}
return string;
}
private String preGet(final String decoded, final String fieldName) {
final String[] fieldsAndValues = decoded.split("(" + this.fieldValuePairDelimiter + ")");
for (final String fieldAndValue : fieldsAndValues) {
if (fieldAndValue.startsWith(fieldName + this.fieldValueDelimiter)) {
return fieldAndValue.split("(" + this.fieldValueDelimiter + ")")[1];
}
}
return null;
}
public static void main(final String[] args) {
final HttpCookieDeSerializer hcds = new HttpCookieDeSerializer();
try {
final HttpCookie cookie = new HttpCookie("myCookie", "first");
final String serializedAndEncoded = hcds.serializeAndEncode(cookie);
// TODO: remove sysout
System.out.println(serializedAndEncoded);
final HttpCookie other = hcds.decodeAndDeserialize(serializedAndEncoded);
// TODO: remove sysout
System.out.println(cookie.equals(other));
} catch (final Throwable t) {
t.printStackTrace();
}
}
}
在我看来,无需编码/或序列化。
但是,如果您想这样做,我建议使用Apache Commons-Codec库的org.apache.commons.codec.binary.Hex
导致其经过测试且稳定的LIB,而无需运行时依赖性,大小约为331KB
永远不会少,Ive尝试了以下序列化和挑选化的可能性
- 没有base64编码/hexing
- 用base64编码
- hexing
- 带有基础-64编码和十六进制
对我来说,所有可能性都很好。