如何根据给出的url字符串和map对象生成对应的携带参数的url字符串?
/oauth/authorize?client_id=baidu&response_type=code&scope=all&redirect_uri=http://www.baidu.com
如上,我们有/oauth/authorize这种url以及包含client_id,scope等的map对象,如何转换为以上的形式
public class Main {
public static void main(String[] args) throws UnsupportedEncodingException {
String baseUrl="http://www.b.com/oauth/authorize";
Map<String,String> map=new HashMap<>();
map.put("client_id",null);
map.put("response_type","code");
map.put("scope","all people");
map.put("redirect_uri","http://www.baidu.com");
String url = appendIfNotContain(baseUrl, "?", "&");
// 将map对象转换为字符串
String paramString = parseMapToString(map, true);
System.out.println(url+paramString);
}
/**
*
* @param str 要拼接的字符串
* @param appendStr 不存在appendStr,就添加 appendStr
* @param otherwise 存在appendStr,就添加 otherwise
* @return
*/
public static String appendIfNotContain(String str, String appendStr, String otherwise) {
if (isEmpty(otherwise)|| isEmpty(appendStr)) {
return str;
}
if (str.contains(appendStr)) {
return str.concat(otherwise);
}
return str.concat(appendStr);
}
/**
*
* @param params map对象
* @param encode 是否进行uri编码,因为url中不允许出现空格等字符
* @return
* @throws UnsupportedEncodingException
*/
public static String parseMapToString(Map<String, String> params, boolean encode) throws UnsupportedEncodingException {
List<String> paramList = new ArrayList();
for (Map.Entry<String, String> entry : params.entrySet()) {
if(entry.getValue()==null){
paramList.add(entry.getKey() + "=");
}else{
// UrlUtil.encode,进行uri编码,注意这个来自于htools工具类
paramList.add(entry.getKey()+"="+(encode ? URLUtil.encode(entry.getValue()): entry.getValue()));
}
}
return String.join("&", paramList);
}
// 判断字符串是否为空
public static boolean isEmpty(String str) {
return null == str || str.isEmpty();
}
}
结果
http://www.b.com/oauth/authorize?scope=all%20people&response_type=code&redirect_uri=http://www.baidu.com&client_id=