如何(正确)在Java中创建mailto URL(URI)?

时间:2015-05-08 21:39:50

标签: java uri mailto

假设:

String email1 = "simple@example.org";

// legal email address according to wikipedia [1]
String email2 = "\"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a\"@example.org";

创建mailto:URI(以String对象的形式)的最佳/正确方法是什么?

我试过了:

String uri = new URI("mailto", the_email_address, null).toString();

这是我最接近的,但它不会在电子邮件地址的本地部分编码问号(?),但根据RFC 6068它应该。它也失败了RFC中的示例,例如&#34;不是@ me&#34; @ example.org 不太可能?address = example.com

[1] Valid_email_addresses examples

PS:Should plus be encoded in mailto: hyperlinks?

中有一些有用的信息

我为此解决了这个问题:

import org.apache.http.client.utils.URIBuilder;
// from Apache HttpClient
// maven group: org.apache.httpcomponents artifact: httpclient

String emailURL = new URIBuilder().setScheme("mailto").setPath(the_email_address).toString();

3 个答案:

答案 0 :(得分:12)

您必须手动对?&进行编码/转义百分比。

String email2 = "\"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a\"@example.org";
String uri2 = (new URI("mailto", email2, null)).toString().replace("?", "%3F").replace("&", "%26");

因此,?&符号似乎未在URI中正确转义。在URI中忽略?之后的任何内容,因为该符号是为&#34;查询字符串&#34;在URL中。参考here

根据this和参考文件,我们也需要逃避&。出于某种原因,Java并没有为我们这样做。事实上,RFC 6068甚至声明:

  

必须出现的许多字符          百分比编码。这些是无法出现的字符          根据[STD66]以及&#34;%&#34;的URI (因为它用于          百分比编码)和gen-delims中的所有字符除了&#34; @&#34;          和&#34;:&#34; (即&#34; /&#34;,&#34;?&#34;,&#34;#&#34;,&#34; [&#34;和&#34;]& #34)。其中的人物          在sub-delims中,至少以下也必须是百分比 -          编码:&#34;&amp;&#34;,&#34;;&#34;和&#34; =&#34;。

修复它的方法(有点像黑客,但它有效)是使用%后跟符号的2位ASCII十六进制值手动转义这些字符。参考this

我通过将生成的字符串粘贴到Chrome中进行测试,并通过电子邮件正确打开了我的默认电子邮件

"()<>[]:,; @\"!#$%&'*+-/=?^_`{}| ~.a"@example.org

更多研究

因此,Java的URI类似乎使用RFC 2396,其中声明:

  

如果URI组件的数据与      保留的目的,然后必须转义冲突的数据      形成URI。

 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
            "$" | ","
     

&#34;保留&#34;上面的语法类是指那些字符      允许在URI中,但可能不允许在      通用URI语法的特定组件;

答案 1 :(得分:4)

您必须使用Apache Commons URI 构建器

  

该值预计未转义,可能包含非ASCII   字符。

你不能直接使用java uri class Java URI doc说所有标点字符都与字符串“?/ [] @”<中的字符串一起保留/ strong> 保留

  

Java的URI类使用RFC 2396,它指出:如果URI组件的数据与      保留的目的,然后必须转义冲突的数据      形成URI。

 reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
            "$" | ","
     

您可以使用java.net.URLEncoder对user_name进行编码,然后再使用   使用编码的用户名创建URI String uri = new URI("mailto", the_email_address, null).toString();   或
  您可以手动百分比编码/转义?和&amp;。

String email2 = "\"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a\"@example.org";
String uri2 = (new URI("mailto", email2, null)).toString().replace("?", "%3F").replace("&", "%26");
     

在JavaScript中,您可以使用encodeURI()功能。 PHP有   rawurlencode()函数,ASP具有Server.URLEncode()函数。


答案 2 :(得分:0)

您可能希望使用URI.create(String uri)静态方法来创建mailto uri,而不是使用“new”构造函数。例如,这会返回一个有效的URI(我使用的是jdk 7):

URI.create("mailto:john?doe@foo.bar.com");

我希望它有所帮助。

干杯。