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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.