URL解析query的坑
本来是想根据url解析参数成Map,结果不留神,留下了个坑.....测试的时候才发现,看来还是对api不是很熟悉,没有注意源码
//...
private static final Pattern PARAM_PATTERN = Pattern.compile("(?<key>\\w+)=(?<value>\\w+)&?");
//...
URL u = getURL(url);
Map<String, String> params = parseQuery2Param(u.getQuery());
//...
private Map<String, String> parseQuery2Param(String query) {
Map<String, String> params = new HashMap<>();
Matcher matcher = PARAM_PATTERN.matcher(query);
while (matcher.find()) {
String key = matcher.group("key");
String value = matcher.group("value");
params.put(key, value);
System.out.println(key + ":" + value);
}
return params;
}
这个本来想着没啥问题,结果当url没有参数的时候,直接返回了null,导致正则出现了问题NPE
看api才知道
/**
* Gets the query part of this {@code URL}.
*
* @return the query part of this {@code URL},
* or <CODE>null</CODE> if one does not exist
* @since 1.3
*/
public String getQuery() {
return query;
}
吃一堑长一智了