In Java webapp, I need an automatic converter to convert String to use in a mailto link
By example, 开发者_运维知识库I have this String "S&D" will be display in a html correctly "S&D". But now I need to have a mailto link in my web page.
<a href="mailto:?subject=my%20subject&body=S&D">share</a>
its wrong character "&", so I need to convert "&" to "%26".
There is a library to do that?
I tried java.net.URLEncoder but she changed only the "&" not the "&" and she replace space " " by plus "+" I tried java.net.URI but she did nothing for character "&"!
Quoting RFC 6068(thanks JB Nizet):
When producing 'mailto' URIs, all spaces SHOULD be encoded as %20, and '+' characters MAY be encoded as %2B. Please note that '+' characters are frequently used as part of an email address to indicate a subaddress, as for example in
<bill+ietf@example.org>
.
Updated code:
String subject = URLEncoder.encode("my subject", "utf-8").replace("+", "%20");
String body = URLEncoder.encode("S&D", "utf-8").replace("+", "%20");
// Email addresses may contain + chars
String email = "test@example.com".replace("+", "%2B");
String link = String.format("mailto:%s?subject=%s&body=%s", email, subject, body);
System.out.println(StringEscapeUtils.escapeHtml(link));
Output:
mailto:test@example.com?subject=my%20subject&body=S%26D
Which may be used in a link like so:
<a href="mailto:test@example.com?subject=my%20subject&body=S%26D">mail me</a>
StringEscapeUtils.escapeHtml(String str) from Apache Commons Lang.
精彩评论