Search code examples
kotlinhttpurlescapingktor

Difference between encodeURLParameter, encodeURLPath and encodeURLQueryComponent?


In Ktor there are those three String extension functions.

Semantically it is almost clear what they do (not completely clear).

In practical terms, I'm not sure what they do.

If I want to encode a part of a url path (like/<<this>>/here) what should I use?

If I want to encode a string that may contain / chars that I dont want escaped (ie hello/beautiful/world)?

If I want to encode a string that contains both / and spaces or http special chars like: this/is seriously/weird?

If I want to encode a string that goes into a query param?

If I want to encode a string that is both the key and the value of a query param?


Solution

  • If I want to encode a part of a url path (like/<<this>>/here) what should I use?

    "<<this>>".encodeURLPathPart()
    

    If I want to encode a string that may contain / chars that I dont want escaped (ie hello/beautiful/world)?

    "hello/beautiful/world".encodeURLPath()
    

    If I want to encode a string that contains both / and spaces or http special chars like: this/is seriously/weird?

    // It depends on how do you want to encode it
    "this/is seriously/weird".encodeURLParameter(spaceToPlus = true)
    "this/is seriously/weird".encodeURLParameter()
    "this/is seriously/weird".encodeURLPathPart()
    

    If I want to encode a string that goes into a query param?

    If I want to encode a string that is both the key and the value of a query param?

    "param key/value".encodeURLQueryComponent(encodeFull = true)