1

I have a URL string with replaceable values:

  http://DOMAIN:PORT/sendmsg?user=test&passwd=test00&text={CONTENT}

I have to encode the content part, so I tried this:

  String tempContent = URLEncoder.encode(content, "UTF-8");

tempContent had this value: This+is+test+one I do not want the + where spaces is. Spaces MUST be represented by %20

Now, I can do this:

  String tempContent = content.replaceAll(" ", "%20");

BUT that only covers the spaces and I don't have control over the content input. Is there any other efficient way to encode URL content in Java? URLEncoder does not do what I want.

Thanks in advance..

lulu88
  • 1,694
  • 5
  • 27
  • 41
  • maybe a duplicate of http://stackoverflow.com/questions/444112/how-do-i-encode-uri-parameter-values – pierroz Jun 06 '13 at 07:31

2 Answers2

2

I finally got this to work, I used

  URIUtil.encodeQuery(url);

Correctly encoded spaces with %20. This comes from the Apache commons-httpclient project.

lulu88
  • 1,694
  • 5
  • 27
  • 41
0

One solution is to use a library which expands URI templates (this is RFC 6570). I know of at least one (disclaimer: this is mine).

Using this library, you can do this:

final URITemplate template
    = new URITemplate("http://DOMAIN:PORT/sendmsg?user=test&passwd=test00&text={CONTENT}");

final VariableValue value = new ScalarValue(content);

final Map<String, VariableValue> vars = new HashMap<String, VariableValue>();
vars.put("CONTENT", value);

// Obtain expanded template
final String s = template.expand(vars);

// Now build a URL out of it

Maps are allowed as values (this is a MapValue in my implementation; the RFC calls these "associative arrays"), so for instance, if you had a map with (correctly filled) entries for user, passwd and text, you could write your template as:

http://DOMAIN:PORT/sendmsg{?parameters*}

With a map value parameters containing:

"user": "john",
"passwd": "doe",
"content": "Hello World!"

this would expand as:

http://DOMAIN:PORT/sendmsg?user=john&passwd=doe&content=Hello%20World%21
fge
  • 119,121
  • 33
  • 254
  • 329