javaspringuriencoding

trying to URIEncode a string in java using URIUtils


I'm trying to URIENcode a string in java using URIUtils of spring framework.

it supposed to be simple as far as I understood but for some reason the string stays unchanged.

I have the following string:

http://www.foo.bar/foo/bar

and I want to URIEncode it.

final String ENC = "UTF-8";
String uri = "http://www.foo.bar/foo/bar";
final String result = UriUtils.encodeFragment(uri, ENC);

the result is the same string not encoded.

what am I doing wrong?

how can I properly URIEncode that string in order to use it in get parameters ?

I don't want to use a URLBuilder because i need to use the resulted output and create a hash table for an internal database.

thank you


Solution

  • I think you can achieve the same using java.net.URLEncoder, avoiding the spring class

    System.out.println(URLEncoder.encode("http://www.foo.bar/foo/bar", "UTF-8"))
    

    would print

    http%3A%2F%2Fwww.foo.bar%2Ffoo%2Fbar