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..
I finally got this to work, I used
URIUtil.encodeQuery(url);
Correctly encoded spaces with %20. This comes from the Apache commons-httpclient project.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.