Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right encoding for `URLEncoder.encode`

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).

like image 972
Daniel Avatar asked Jun 18 '15 22:06

Daniel


1 Answers

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

val query = "http://localhost:8080/ask?text=" + URLEncoder.encode(text, "UTF-8")
like image 197
JB Nizet Avatar answered Oct 01 '22 01:10

JB Nizet