How to convert map to url query string?

前端 未结 17 1492
盖世英雄少女心
盖世英雄少女心 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<String, String> 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));
    
    0 讨论(0)
  • 2020-11-27 14:10

    Kotlin

    mapOf(
      "param1" to 12,
      "param2" to "cat"
    ).map { "${it.key}=${it.value}" }
      .joinToString("&")
    
    0 讨论(0)
  • 2020-11-27 14:13

    Using EntrySet and Streams:

    map
      .entrySet()
      .stream()
      .map(e -> e.getKey() + "=" + e.getValue())
      .collect(Collectors.joining("&"));
    
    0 讨论(0)
  • 2020-11-27 14:13

    For multivalue map you can do like below (using java 8 stream api's)

    Url encoding has been taken cared in this.

    MultiValueMap<String, String> params =  new LinkedMultiValueMap<>();
    String urlQueryString = params.entrySet()
                .stream()
                .flatMap(stringListEntry -> stringListEntry.getValue()
                        .stream()
                        .map(s -> UriUtils.encode(stringListEntry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +
                                UriUtils.encode(s, StandardCharsets.UTF_8.toString())))
                .collect(Collectors.joining("&"));
    
    0 讨论(0)
  • 2020-11-27 14:17

    If you actually want to build a complete URI, try URIBuilder from Apache Http Compoments (HttpClient 4).

    This does not actually answer the question, but it answered the one I had when I found this question.

    0 讨论(0)
  • 2020-11-27 14:17

    I wanted to build on @eclipse's answer using java 8 mapping and reducing.

     protected String formatQueryParams(Map<String, String> params) {
          return params.entrySet().stream()
              .map(p -> p.getKey() + "=" + p.getValue())
              .reduce((p1, p2) -> p1 + "&" + p2)
              .map(s -> "?" + s)
              .orElse("");
      }
    

    The extra map operation takes the reduced string and puts a ? in front only if the string exists.

    0 讨论(0)
提交回复
热议问题