在包含变音符号的Java中解析URI的主机

lex*_*x82 4 java uri

我正在尝试从主机中包含字符'ü'的URI解析主机,如下所示:

String host = new java.net.URI("http://füllmethodentafel.de").getHost();
Run Code Online (Sandbox Code Playgroud)

但是,主机将为null.它适用于其他URI.任何想法为什么它不起作用?

小智 5

java.net.URI只能解析符合RFC 2396的 URL .此RFC需要以下规则:

  hostport      = host [ ":" port ]
  host          = hostname | IPv4address
  hostname      = *( domainlabel "." ) toplabel [ "." ]
  domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
  toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
Run Code Online (Sandbox Code Playgroud)

alphanum基本上是哪里[a-zA-Z0-9].像这样ü的人物不包括在内.

URI 可以处理相当于的 PunycodeURL .为此,很有用.http://www.xn--hostwith-e6a.com/http://www.hostwithü.com/java.net.IDN

String host = "www.hostwithü.com";
String toASCII = IDN.toASCII(host);
System.out.println(toASCII);
// www.xn--hostwith-e6a.com
Run Code Online (Sandbox Code Playgroud)