Hi, is there a way to encode query params with a s...
# http4k
r
Hi, is there a way to encode query params with a specific encoding, for instance UTF-8?
1
d
Http4k will just URL encode whatever it is given. Can you expand on what your trying to do with an example?
r
In the following function, I’m sending “search”, which may contain accents, as a query param. I would like to give the precision to encode it using UTF-8. My tests showed that the default encoding is ISO8851 and I would like to change it, with a configuration in HTTP4K
Copy code
override fun find(search: String?, roles: String?, customerAccountId: String?, limit: Int?): List<User> =
        this.httpClient(
            Request(Method.GET, "$baseUrl/users")
                .query("search", search)
                .query("roles", roles?.replace("DEMONSTRATION", "ANIMATOR"))
                .query("limit", limit?.toString())
                .let { if (customerAccountId !== null) it.query("customerAccountRef", customerAccountId) else it })
            .takeIf { it.status == OK }
            ?.let(userListLens)
            ?.map { it.toDomain() }
            ?: listOf()
j
I think URI can only contain characters in us-ascii. Everything else has to be encoded. The rules are here... https://www.rfc-editor.org/rfc/rfc3986#section-2.4. Section 1.2.1? Maybe
d
@Ryunos The best way would be to use a custom base lens that can be reused. Not sure if this works as you need, but the idea would be the same:
Copy code
fun <T : HttpMessage> BiDiLensSpec<T, String>.convert(from: Charset, to: Charset) =
        map({ String(it.toByteArray(from), to) }, { String(it.toByteArray(from), to) })

    val queryLens = Query.convert(UTF_8, ISO_8859_1).required("foo")
    val headerLens = Header.convert(UTF_8, ISO_8859_1).required("bar")

    Request(GET, "<http://someurl>").with(queryLens of "hello", headerLens of "world")
You can't globally override the charset in http4k, regardless of if it's with or against the spec 🙂
r
Thank you @dave, looks like it is exactly what I need! 😄
269 Views