The right encoding for `URLEncoder.encode`

13.2k Views Asked by At

I am trying to standardize the messages in my URLs and I am using URLEncoder.encode. The problem I get is that, the output does not seem to be a valid URL. For example

val text = Some("test question (a) x (b) y").get
val query = "http://localhost:8080/ask?text=" + text
println(query)
val queryEnc = URLEncoder.encode(query, "UTF-8")
println(queryEnc)

which outputs:

http://localhost:8080/ask?text=test question (a) x (b) y
http%3A%2F%2Flocalhost%3A8080%2Fask%3Ftext%3Dtest+question+%28a%29+x+%28b%29+y

Is the output a valid URL? (it doesn't look to be valid, as Chrome and Safari on my machine don't recognize it).

1

There are 1 best solutions below

1
On BEST ANSWER

You must encode each parameter value. Not the whole URL.

val query = "http://localhost:8080/ask?text=" + URLEncoder.encode(text, "UTF-8")