How can one easily build an url having queryParame...
# spring
p
How can one easily build an url having queryParameters if I have the queryParams in a simple
val params= mapOf("foo" to "bar")
, how can I pass it to an
UriComponentBuilder
?
1
k
Copy code
val uri = UriComponentsBuilder.newInstance()
        .scheme("http")
        .host("<http://example.org|example.org>")
        .path("example/path")
        .query("fn={firstName}")
        .query("sn={surname}")
        .buildAndExpand(mapOf("firstName" to "John", "surname" to "Smith"))
        .toUri()
p
Thanks. It seems that you have to map the map keys (eg
firstName
) to query parameters (
fn
). Isn't there a one-stop solution, so that if I have
mapOf("foo" to "bar", "ping" to "pong")
it would just become
?foo=bar&ping=pong
without further instruction?
k
I see. There are two ways:
Copy code
val uriComponents1 = UriComponentsBuilder.newInstance()
        .scheme("http")
        .host("<http://example.org|example.org>")
        .path("example/path")
        .queryParams(CollectionUtils.toMultiValueMap(originalMap.mapValues { listOf(it.value) }))
        .build()
    val uri1 = uriComponents1.toUri()
    println(uri1)

    val uriComponents2 = UriComponentsBuilder.newInstance()
        .scheme("http")
        .host("<http://example.org|example.org>")
        .path("example/path")
        .apply {
            originalMap.forEach { (k, v) -> queryParam(k, v) }
        }
        .build()
    val uri2 = uriComponents2.toUri()
    println(uri2)
p
Ah thanks, seems to be there is no one-stop solution for that. CollectionUtils could have some method for this purpose. Since that is implemented, I'll go for your second solution. Thanks