Map与Url查询参数相互转换

作者: adm 分类: java 发布时间: 2021-07-13

导包

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
/**
* map 与 url参数转换
*/
public class MapUrlParamsUtils {
/**
* 将url参数转换成map
*
* @param param aa=11&bb=22&cc=33
* @return
*/
public static Map<String, Object> getUrlParams(String param) {
Map<String, Object> map = new HashMap<String, Object>(0);
if (StringUtils.isBlank(param)) {
return map;
}
String[] params = param.split("&");
for (int i = 0; i < params.length; i++) {
String[] p = params[i].split("=");
if (p.length == 2) {
map.put(p[0], p[1]);
}
}
return map;
}
/**
* 将map转换成url
*
* @param map
* @return
*/
public static String getUrlParamsByMap(Map<String, Object> map) {
if (map == null) {
return "";
}
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : map.entrySet()) {
sb.append(entry.getKey() + "=" + entry.getValue());
sb.append("&");
}
String s = sb.toString();
if (s.endsWith("&")) {
s = StringUtils.substringBeforeLast(s, "&");
}
return s;
}
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!