trying to URIEncode a string in java using URIUtils

11k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

There is an RFC which allows URI building from different parameters: URI templates.

Since you use Java, there happens to be an implementation available (disclaimer: yes it's mine).

You could then do like this:

// The template
final URITemplate tmpl = new URITemplate("http://my.site/foo{?params*}");

// The query parameters
// Uses Maps from Guava since the lib depends on it
final Map<String, String> params = Maps.newHashMap();
params.put("site", "http://www.foo.bar/foo/bar");

// The template data expansion
final Map<String, VariableValue> data = Maps.newHashMap();
data.put("params", new MapValue(params));

// Expand, build the URL
// The expansion takes care of all the encoding for you
final URL url = new URL(template.expand(data));