今天項目中遇到了一個問題,同樣的使用Base64 encode的時候,發現有二個Base64類可以encode,使用misc的 BASE64Encoder 方法 encode,生成的String和util包的Base64生成String有什么區別呢?
寫了個程序,把一段內容使用不同的方法encode,如下圖所示:misc的Base64會自動加\n, 為什么要這樣呢?
簡單事例代碼:
byte[] bytes = new byte[57]; String enc1 = new sun.misc.BASE64Encoder().encode(bytes); String enc2 = new String(java.util.Base64.getMimeEncoder().encode(bytes), StandardCharsets.UTF_8); System.out.println("enc1 = <" + enc1 + ">"); System.out.println("enc2 = <" + enc2 + ">"); System.out.println(enc1.equals(enc2));
輸出:
byte[] bytes = new byte[57]; String enc1 = new sun.misc.BASE64Encoder().encode(bytes); String enc2 = new String(java.util.Base64.getMimeEncoder().encode(bytes), StandardCharsets.UTF_8); System.out.println("enc1 = <" + enc1 + ">"); System.out.println("enc2 = <" + enc2 + ">"); System.out.println(enc1.equals(enc2));
sun.misc.BASE64Encoder encode時每76個字符就會生成一個'\n',java.util.Base64不會有換行符的產生。
java.util.Base64的作者認為 sun.misc.BASE64Encoder 這個做法是個bug,我也認為是的,因為在我使用sun.misc.BASE64Encoder encode之后的String,在HTTP請求Head中放時 \n HTTP請求檢查頭部參數會報錯,不認換行符。