All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.tool.utils.UrlUtil Maven / Gradle / Ivy

There is a newer version: 1.3.2
Show newest version
package top.doudou.common.tool.utils;

import java.util.Map;
import java.util.Set;

import static top.doudou.common.tool.bean.ConvertBeanUtils.convertBean2Map;
import static top.doudou.common.tool.bean.ConvertBeanUtils.convertMap;

/**
 * @Description url工具类
 * @Author 傻男人 <[email protected]>
 * @Date 2020-09-28 16:02
 * @Version V1.0
 */
public class UrlUtil {
    /**
     * Get url join
     *
     * @param url    base url
     * @param params params
     * @return String
     */
    public static String urlJoin(String url, Map params) {
        if (null == params) {
            return url;
        }
        StringBuilder endUrl = new StringBuilder(url);
        boolean isFirst = true;
        Set> entrySet = params.entrySet();
        for (Map.Entry entry : entrySet) {
            if (isFirst && !url.contains("?")) {
                isFirst = false;
                endUrl.append("?");
            } else {
                endUrl.append("&");
            }
            endUrl.append(entry.getKey());
            endUrl.append("=");
            endUrl.append(entry.getValue());
        }
        return endUrl.toString();
    }

    /**
     * 将实体类转换为参数拼接在url后面
     * @param url  请求的地址
     * @param entity  实体类
     * @return
     */
    public static   String createUrl(String url,E entity){
        Map map = convertMap(convertBean2Map(entity));
        return urlJoin(url,map);
    }

    /**
     * 将url中的占位符替换成map中的参数,需要占位符与map中的key对应
     * @param url 请求的地址
     * @param parameters
     * @return
     */
    public static String createUrl(String url, Map parameters){
        Set keys = parameters.keySet();
        for(String key : keys){
            url = url.replace("{"+key+"}",parameters.get(key));
        }
        return url;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy