Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do url encoding for query parameters in Kotlin

I am new to Kotlin & I am trying to url encode my url which has query parameters.

private const val HREF = "date?July 8, 2019"
private const val ENCODED_HREF = print(URLEncoder.encode(HREF, "utf-8"))
private const val URL = "www.example.com/"+"$ENCODED_HREF"

Error: Const 'val' has type 'Unit'. Only primitives and Strings are allowed for private const val ENCODED_HREF

like image 590
Mia Avatar asked Jul 08 '19 20:07

Mia


People also ask

Should query parameters be URL encoded?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing them into a URL.

What is %20 in query string?

%20 is an encoded ' ' (blank). %26 is an encoded '&' (ampersand). See "HTML URL Encoding Reference"[^]. Instead of removing them, you probably should convert them back to blank and ampersand instances.

How do I encode a URL in query string?

URL Encoding is used when placing text in a query string to avoid it being confused with the URL itself. It is normally used when the browser sends form data to a web server. URL Encoding replaces “unsafe” characters with '%' followed by their hex equivalent.


2 Answers

const expressions in Kotlin must be known at compile time. Also, as @Stanislav points out, print is a Unit (i.e., void in Java) method, so printing something destroys its value.

Since your constants are computed, the use of val (which is a runtime constant) is appropriate. The following compiles.

private const val HREF = "date?July 8, 2019"
private val ENCODED_HREF = java.net.URLEncoder.encode(HREF, "utf-8")
private val URL = "www.example.com/"+"$ENCODED_HREF"
like image 86
David P. Caldwell Avatar answered Sep 24 '22 09:09

David P. Caldwell


Seems like the returning type of the print method is Unit, so that's why ENCODED_HREF has this type. Just take the URLEncoder part out of the method to fix it:

private const val ENCODED_HREF = URLEncoder.encode(HREF, "utf-8")
like image 22
Stanislav Shamilov Avatar answered Sep 24 '22 09:09

Stanislav Shamilov