How to convert map to url query string?

前端 未结 17 1571
盖世英雄少女心
盖世英雄少女心 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:10

    Personally, I'd go for a solution like this, it's incredibly similar to the solution provided by @rzwitserloot, only subtle differences.

    This solution is small, simple & clean, it requires very little in terms of dependencies, all of which are a part of the Java Util package.

    Map map = new HashMap<>();
    
    map.put("param1", "12");
    map.put("param2", "cat");
    
    String output = "someUrl?";
    output += map.entrySet()
        .stream()
        .map(x -> x.getKey() + "=" + x.getValue() + "&")
        .collect(Collectors.joining("&"));
    
    System.out.println(output.substring(0, output.length() -1));
    

提交回复
热议问题