一:
import java.io.UnsupportedEncodingException;
/**
* BASE64编解码工具
*/
public class Base64Util {
/**
* BASE64编码
*
* @param stringbyte
* @return
*/
public static String encrypt(byte[] stringbyte) {
String result = null;
if (null!=stringbyte) {
result = new sun.misc.BASE64Encoder().encode(stringbyte);
}
return result;
}
/**
* BASE64编码
*
* @param string
* 要编码的字符串
* @param charsetName
* 字符串编码
* @return
*/
public static String encrypt(String string, String charsetName) {
String result = null;
if (ObjectUtil.isNotEmpty(string)) {
byte[] stringbyte = null;
try {
stringbyte = string.getBytes(charsetName);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("请使用正确的编码");
}
result = encrypt(stringbyte);
}
return result;
}
/**
* BASE64解码
*
* @param base64
* 待解码字符串
* @return
*/
public static byte[] decrypt(String base64) {
byte[] result = null;
if (ObjectUtil.isNotEmpty(base64)) {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
try {
result = decoder.decodeBuffer(base64);
} catch (Exception e) {
throw new RuntimeException("解码失败");
}
}
return result;
}
/**
* BASE64解码
*
* @param base64
* 待解码字符串
* @param charsetName
* 解码后字符串编码方式
* @return
*/
public static String decrypt(String base64, String charsetName) {
String result = null;
try {
result = new String(decrypt(base64), charsetName);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("请使用正确的编码");
}
return result;
}
}
二:使用
//queryString为64编码之后的字符串,例如http后面的参数:idcard=330501197211067128&diagnosisCode=A20.200&fillOrganCode=SZ586004
1. Map<String, Object[]> paramMap = decrypt(queryString);
2. public Map<String, Object[]> decrypt(String queryString) {
//先用UTF-8解析看有没有编码参数
Map<String, Object[]> map = null;
String parameters = "";
parameters = Base64Util.decrypt((queryString.replaceAll(" ","+")), "UTF-8");
if (ObjectUtil.isNotEmpty(parameters)){
try{
map = convertQueryToReport(parameters);
}catch (Exception e) {
logger.error("参数解析失败", e);
}
}
return map;
}
3.
/**
* 将参数字符串转换为map
* @param query=idcard=330501197211067128&diagnosisCode=A20.200&fillOrganCode=SZ586004
* @return
*/
private Map<String, Object[]> convertQueryToReport(String query) {
Map<String, Object[]> map = new HashMap<String, Object[]>();
String params[] = query.split("&");
for (String param : params) {
if (param.indexOf("=") > 0) {
String keyValues[] = param.split("=");
if (keyValues.length == 2) {
String value=keyValues[1] ;
value=value==null?"":value.trim();
map.put(keyValues[0], new Object[] { value});
} else if (keyValues.length == 1) {
map.put(keyValues[0], new Object[] { "" });
}
}
}
return map;
}