50,530
社区成员
发帖
与我相关
我的任务
分享
ab=12&cd={ef=gh&ij=kl}&ml=op
ab=12
cd={ef=gh&ij=kl}
ml=op
/**
* 解析应答字符串,生成应答要素
*
* @param str
* 需要解析的字符串
* @return 解析的结果map
* @throws UnsupportedEncodingException
*/
public static Map<String, String> parseQString(String str)
throws UnsupportedEncodingException {
Map<String, String> map = new HashMap<String, String>();
int len = str.length();
StringBuilder temp = new StringBuilder();
char curChar;
String key = null;
boolean isKey = true;
int add = 1;
for (int i = 0; i < len; i++) {// 遍历整个带解析的字符串
curChar = str.charAt(i);// 取当前字符
if (curChar == '&') {// 如果读取到&分割符
if (add==2) {
temp.append(curChar);
}else {
putKeyValueToMap(temp, isKey, key, map);
temp.setLength(0);
isKey = true;
}
} else {
if (curChar == '{') {
add = 2;
}
if (curChar == '}') {
add = 3;
}
if (isKey) {// 如果当前生成的是key
if (curChar == '=') {// 如果读取到=分隔符
key = temp.toString();
temp.setLength(0);
isKey = false;
} else {
temp.append(curChar);
}
} else {// 如果当前生成的是value
temp.append(curChar);
}
}
}
putKeyValueToMap(temp, isKey, key, map);
return map;
}
private static void putKeyValueToMap(StringBuilder temp, boolean isKey,
String key, Map<String, String> map)
throws UnsupportedEncodingException {
if (isKey) {
key = temp.toString();
if (key.length() == 0) {
throw new RuntimeException("QString format illegal");
}
map.put(key, "");
} else {
if (key.length() == 0) {
throw new RuntimeException("QString format illegal");
}
map.put(key, URLDecoder.decode(temp.toString(), UpmpConfig.CHARSET));
}
}