在Android提供的android.util.Base64类中,提供了base64基本的几种编解码格式,源码如下
/**
* Default values for encoder/decoder flags.
*/
public static final int DEFAULT = 0; // 此flag下编码完成的String中会包含换行符\n,+号,末尾以“=”结束
/**
* Encoder flag bit to omit the padding '=' characters at the end
* of the output (if any).
*/
public static final int NO_PADDING = 1; //此flag下最终的编码字符串会包含换行符\n,但是末尾去掉了“=”
/**
* Encoder flag bit to omit all line terminators (i.e., the output
* will be on one long line).
*/
public static final int NO_WRAP = 2; // 此flag下最终编码字符串不包含换行符\n,+号,且字符串全在一行,设置此flag后CRLF flag无效
/**
* Encoder flag bit to indicate lines should be terminated with a
* CRLF pair instead of just an LF. Has no effect if {@code
* NO_WRAP} is specified as well.
*/
public static final int CRLF = 4; // 编码后用CR LF这一对作为一行末尾的换行,而不是unix风格的LF换行
/**
* Encoder/decoder flag bit to indicate using the "URL and
* filename safe" variant of Base64 (see RFC 3548 section 4) where
* {@code -} and {@code _} are used in place of {@code +} and
* {@code /}.
*/
public static final int URL_SAFE = 8; // 编码后,用-代替+,用_代替·/,避免请求是url编码造成的传输问题,包含换行符\n
/**
* Flag to pass to {@link Base64OutputStream} to indicate that it
* should not close the output stream it is wrapping when it
* itself is closed.
*/
public static final int NO_CLOSE = 16;
附上Base64的元码表【from wiki】
小结
用flag Default编码后,字符串中带有+号和\n换行符,发起网络请求时,当以base64字符串作为参数值传递时,url为了传输安全会把+号全部变成空格,在接收端就会产生各种问题,且前端用的部分的Base64解码库不支持\n,当字符串中含有\n时无法解码还原为图片。所以Base64编码时建议使用NO_WRAP | URL_SAFE,这样可以避免较多问题。