mirror of
https://gitee.com/dromara/hutool.git
synced 2025-04-05 17:37:59 +08:00
commit
2dd90253e2
@ -24,6 +24,35 @@ public class PunyCode {
|
||||
|
||||
public static final String PUNY_CODE_PREFIX = "xn--";
|
||||
|
||||
/**
|
||||
* punycode转码域名
|
||||
* @param domain
|
||||
* @return
|
||||
* @throws UtilException
|
||||
*/
|
||||
public static String encodeDomain(String domain) throws UtilException{
|
||||
Assert.notNull(domain, "domain must not be null!");
|
||||
String[] split = domain.split("\\.");
|
||||
StringBuilder outStringBuilder = new StringBuilder();
|
||||
for (String string: split) {
|
||||
boolean encode = false;
|
||||
for (int index=0; index<string.length(); index++) {
|
||||
char c = string.charAt(index);
|
||||
if (!isBasic(c)) {
|
||||
encode = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (encode) {
|
||||
outStringBuilder.append(PunyCode.encode(string, true));
|
||||
} else {
|
||||
outStringBuilder.append(string);
|
||||
}
|
||||
outStringBuilder.append(".");
|
||||
}
|
||||
return outStringBuilder.substring(0, outStringBuilder.length() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将内容编码为PunyCode
|
||||
*
|
||||
@ -119,6 +148,27 @@ public class PunyCode {
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码punycode域名
|
||||
* @param domain
|
||||
* @return
|
||||
* @throws UtilException
|
||||
*/
|
||||
public static String decodeDomain(String domain) throws UtilException{
|
||||
Assert.notNull(domain, "domain must not be null!");
|
||||
String[] split = domain.split("\\.");
|
||||
StringBuilder outStringBuilder = new StringBuilder();
|
||||
for (String string: split) {
|
||||
if (string.startsWith(PUNY_CODE_PREFIX)) {
|
||||
outStringBuilder.append(decode(string));
|
||||
} else {
|
||||
outStringBuilder.append(string);
|
||||
}
|
||||
outStringBuilder.append(".");
|
||||
}
|
||||
return outStringBuilder.substring(0, outStringBuilder.length() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码 PunyCode为字符串
|
||||
*
|
||||
|
@ -15,4 +15,12 @@ public class PunyCodeTest {
|
||||
decode = PunyCode.decode("xn--Hutool-ux9js33tgln");
|
||||
Assert.assertEquals(text, decode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeEncodeDomainTest(){
|
||||
String domain = "赵新虎.中国";
|
||||
String strPunyCode = PunyCode.encodeDomain(domain);
|
||||
String decode = PunyCode.decodeDomain(strPunyCode);
|
||||
Assert.assertEquals(decode, domain);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user