实现说明
IDN 国际化域名 Punycode 与 Unicode 互转可以归结为类 PunycodeDomains和函数 main。
for (String host : hosts) 承担全部的逐项处理。
使用要点
- 内部高度闭合——除了标准运行时原有模块之外别无其他引入。
- 每一步打印都带着自己的标签:
permissive underscore:、STD3 rejected underscore:。
常见问题
运行「IDN 国际化域名 Punycode 与 Unicode 互转」会打印什么?
运行文件本身,permissive underscore:、STD3 rejected underscore: 这些前缀各对应一段演示逻辑。
入口签名:public static void main(String[] args)
核心语句
String[] hosts = { "bücher.example", "例え.jp", "api.example.com" };
String ascii = IDN.toASCII(host, IDN.USE_STD3_ASCII_RULES);
IDN.toASCII("bad_host.example", IDN.USE_STD3_ASCII_RULES);
代码示例
import java.net.IDN;
public class PunycodeDomains {
public static void main(String[] args) {
String[] hosts = { "bücher.example", "例え.jp", "api.example.com" };
for (String host : hosts) {
// toASCII encodes non-ASCII labels into RFC 3490 Punycode (xn--...)
String ascii = IDN.toASCII(host, IDN.USE_STD3_ASCII_RULES);
String roundtrip = IDN.toUnicode(ascii);
System.out.println(host + " -> " + ascii + " -> " + roundtrip);
}
// Default mode permits underscores; USE_STD3_ASCII_RULES restricts to LDH host chars
String permissive = IDN.toASCII("bad_host.example");
System.out.println("permissive underscore: " + permissive);
try {
IDN.toASCII("bad_host.example", IDN.USE_STD3_ASCII_RULES);
} catch (IllegalArgumentException ex) {
System.out.println("STD3 rejected underscore: " + ex.getClass().getSimpleName());
}
}
}