How to convert map to url query string?

前端 未结 17 1538
盖世英雄少女心
盖世英雄少女心 2020-11-27 13:39

Do you know of any utility class/library, that can convert Map into URL-friendly query string?

Example:

I have a map:

\"param1\"=12,
\"param2         


        
17条回答
  •  抹茶落季
    2020-11-27 14:34

    I think this is better for memory usage and performance, and I want to send just the property name when the value is null.

    public static String toUrlEncode(Map map) {
        StringBuilder sb = new StringBuilder();
        map.entrySet().stream()
                .forEach(entry
                        -> (entry.getValue() == null
                        ? sb.append(entry.getKey())
                        : sb.append(entry.getKey())
                                .append('=')
                                .append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8)))
                        .append('&')
                );
        sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }
    

提交回复
热议问题