I have a Java object that is serializable. I need to let another Java webapp do something with this object. I'm currently using this setup to transfer the object:
- Use a ByteArrayOutputStream
baos
- Put the baos in an ObjectOutputStream
oos
- Write the object using the
oos
, and get thebyte[]
from thebaos
- Use a Base64 encoder to encode the byte[] to another byte[]
- send the bytes using a
httpurlconnection
(POST method) - at the receiving end, I do steps 1 to 4 backwards to get my object back.
This works! However, I'm not sure what step 4, the BASE64 encoding is really doing here. Can't I just send the plain bytes in request's body? What are advantages / safety measures that I get with using the Base64 encoding/decoding?
Here's the relevant code snippet described in step 1-4 I found in this other question.
/** Read the object from Base64 string. */
private static Object fromString( String s ) throws IOException, ClassNotFoundException {
byte [] data = Base64.getDecoder().decode( s );
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
private static String toString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}