0
votes

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:

  1. Use a ByteArrayOutputStream baos
  2. Put the baos in an ObjectOutputStream oos
  3. Write the object using the oos, and get the byte[] from the baos
  4. Use a Base64 encoder to encode the byte[] to another byte[]
  5. send the bytes using a httpurlconnection (POST method)
  6. 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()); 
    }
}
1
You can send binary, base64 is not mandatoryMarged

1 Answers

1
votes

The purpose of Base64 is to convert a byte array into a human readable (and universally compatible) format.

Because the underlying stream sends data via bytes, and there is no risk of losing data (eg printing to console a control character is not copy/pasteable), there is no point in converting the bytes to Base64. You get no benefits except for possible future compatibility if you change your network protocol to something else that suffers from being unable to transmit non-printable chars.