java.net.URI使用下划线获取主机 [英] java.net.URI get host with underscores
问题描述
该方法的行为很奇怪:
import java.net.URI
URI url = new URI("https://pmi_artifacts_prod.s3.amazonaws.com");
System.out.println(url.getHost()); /returns NULL
URI url2 = new URI("https://s3.amazonaws.com");
System.out.println(url2.getHost()); //returns s3.amazonaws.com
`
我希望第一个url.getHost()
是pmi_artifacts_prod.s3.amazonaws.com,但这给了我NULL.原来,问题出在域名下划线,这是一个已知的错误,但是仍然需要做些什么,因为我需要确切地使用此主机?
i want first url.getHost()
to be pmi_artifacts_prod.s3.amazonaws.com, but it gives me NULL. Turned out that problem is with underscores in domain name, its a known bug, but still what can be done as I need to work with this host exactly?
推荐答案
该错误不在Java中,而在于命名主机,因为下划线不是主机名中的有效字符.尽管广泛使用不当,但Java拒绝处理此类主机名.
The bug is not in Java but in naming the host, since an underscore is not a valid character in a hostname. Although widely used incorrectly, Java refuses to handle such hostnames.
https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
可能的解决方法:
public static void main(String...a) throws URISyntaxException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
URI url = new URI("https://pmi_artifacts_prod.s3.amazonaws.com");
System.out.println(url.getHost()); //NULL
URI uriObj = new URI("https://pmi_artifacts_prod.s3.amazonaws.com");
if (uriObj.getHost() == null) {
final Field hostField = URI.class.getDeclaredField("host");
hostField.setAccessible(true);
hostField.set(uriObj, "pmi_artifacts_prod.s3.amazonaws.com");
}
System.out.println(uriObj.getHost()); //pmi_artifacts_prod.s3.amazonaws.com
URI url2 = new URI("https://s3.amazonaws.com");
System.out.println(url2.getHost()); //s3.amazonaws.com
}
这篇关于java.net.URI使用下划线获取主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!