Android端在编码过程中尤其涉及到加解密我们通常将加解密后的byte字节数组转换为String,通常做法是使用Android 提供的Base64(android.util)的encodeToString函数:
String strData = Base64.encodeToString(encryptData,Base64.DEFAULT);
那么这其中的flags到底是什么意思?作用是什么呢?
通过源码可见flags取值范围如下:
/**
*编码后用CR LF这一对作为一行末尾的换行,而不是unix风格的LF换行
**/
public static final int CRLF = 4;
/**
*此flag下编码完成的String中会包含换行符\n,+号,末尾以“=”结束
**/
public static final int DEFAULT = 0;
/**
*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;
/**
*此flag下最终的编码字符串会包含换行符\n,但是末尾去掉了“=”
**/
public static final int NO_PADDING = 1;
/**
*此flag下最终编码字符串不包含换行符\n,且字符串全在一行,设置此flag后CRLF flag无效
**/
public static final int NO_WRAP = 2;
/**
*编码后,用-代替+,用_代替/,避免请求是url编码造成的传输问题,包含换行符\n
**/
public static final int URL_SAFE = 8;
PS:可以结合使用满足我们不同需求:
Base64.encodeToString(encryptData,Base64.DEFAULT|Base64.NO_WRAP|Base64.URL_SAFE);
小结
用flag Default编码后,字符串中带有+号和\n换行符,发起网络请求时,当以base64字符串作为参数值传递时,url为了传输安全会把+号全部变成空格,在接收端就会产生各种问题,且前端用的部分的Base64解码库不支持\n,当字符串中含有\n时无法解码还原为图片。所以Base64编码时建议使用NO_WRAP | URL_SAFE,这样可以避免较多问题。