Merge pull request #2543 from zhaoxinhu/v5-dev

V5 dev
This commit is contained in:
Golden Looly 2022-08-20 01:06:59 +08:00 committed by GitHub
commit 2dd90253e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View File

@ -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为字符串
*

View File

@ -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);
}
}