package com.docus.server.rpc.util;

import com.docus.core.util.Func;

import java.util.HashMap;
import java.util.Map;

public class HttpUrlUtil {
    /**
     * 添加url参数
     *
     * @param url   url
     * @param param 参数
     * @return 处理过后的url
     */
    public static String addUrlParam(String url, Map<String, String> param) {
        if (Func.isEmpty(param)) {
            return url;
        }
        StringBuilder urlBuilder = new StringBuilder(url);
        // url已经添加过参数的标记
        String addFlag = "?";
        // url 参数连接符号，如果没有添加过，连接符号置为空
        String connect = "&";
        if (!url.contains(addFlag)) {
            urlBuilder.append("?");
            connect = "";
        }

        for (Map.Entry<String, String> entry : param.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            urlBuilder.append(connect).append(key).append("=").append(value);
            // 添加过参数，连接符置为&
            connect = "&";

        }
        return urlBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(addUrlParam("http://www.baidu.com", null));
        System.out.println(addUrlParam("http://www.baidu.com?word=1", null));
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("en","some");
        System.out.println(addUrlParam("http://www.baidu.com", stringStringHashMap));
        System.out.println(addUrlParam("http://www.baidu.com?word=1", stringStringHashMap));
    }
}
