How to convert map to url query string?

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

    You can use a Stream for this, but instead of appending query parameters myself I'd use a Uri.Builder. For example:

    final Map map = new HashMap<>();
    map.put("param1", "cat");
    map.put("param2", "12");
    
    final Uri uri = 
        map.entrySet().stream().collect(
            () -> Uri.parse("relativeUrl").buildUpon(),
            (builder, e) -> builder.appendQueryParameter(e.getKey(), e.getValue()),
            (b1, b2) -> { throw new UnsupportedOperationException(); }
        ).build();
    
    //Or, if you consider it more readable...
    final Uri.Builder builder = Uri.parse("relativeUrl").buildUpon();
    map.entrySet().forEach(e -> builder.appendQueryParameter(e.getKey(), e.getValue())
    final Uri uri = builder.build();
    
    //...    
    
    assertEquals(Uri.parse("relativeUrl?param1=cat¶m2=12"), uri);
    

提交回复
热议问题