如何根据给出的url字符串和map对象生成对应的携带参数的url字符串?

如何根据给出的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=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值