Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding parameters values in a URL with Java

I need to encode the parameters values in an URL. If I use following:

URLEncoder.encode(url, "UTF-8");

for a URL like this: http://localhost:8080/...

it will encode "://" etc. What I need is the encoding only for the values of the parameters starting from all the URL string. So in this case:

http://localhost/?q=blah&d=blah

I want encoded only the "blah" in the 2 parameters values (for n parameters of course).

What's your best way?

Thanks

Randomize

like image 776
Randomize Avatar asked Sep 21 '11 16:09

Randomize


2 Answers

You're using URLEncoder in a wrong way. You're supposed to encode every parameter value separately and then assemble the url together.

For example


String url = "http://localhost/?q=" + URLEncoder.encode ("blah", "UTF-8") + "&d=" + URLEncoder.encode ("blah", "UTF-8");
like image 148
Andrei LED Avatar answered Oct 14 '22 05:10

Andrei LED


For a URL like http://localhost/hello/sample?param=bla, you could use this (from Java's java.net.URI class):

URI uri = new URI("http", "localhost", "/hello/sample", "param=bla", null);
String url = uri.toASCIIString();
like image 33
Saket Avatar answered Oct 14 '22 04:10

Saket