How to convert map to url query string?

前端 未结 17 1567
盖世英雄少女心
盖世英雄少女心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 14:19

    There's nothing built into java to do this. But, hey, java is a programming language, so.. let's program it!

    map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"))
    

    This gives you "param1=12¶m2=cat". Now we need to join the URL and this bit together. You'd think you can just do: URL + "?" + theAbove but if the URL already contains a question mark, you have to join it all together with "&" instead. One way to check is to see if there's a question mark in the URL someplace already.

    Also, I don't quite know what is in your map. If it's raw stuff, you probably have to safeguard the call to e.getKey() and e.getValue() with URLEncoder.encode or similar.

    Yet another way to go is that you take a wider view. Are you trying to append a map's content to a URL, or... are you trying to make an HTTP(S) request from a java process with the stuff in the map as (additional) HTTP params? In the latter case, you can look into an http library like OkHttp which has some nice APIs to do this job, then you can forego any need to mess about with that URL in the first place.

提交回复
热议问题