使用汉字从URL获取图像

Jor*_*ens 4 java url internationalization character-encoding

我想从远程URL获取图像.

String url =  "http://?.??/images/wonton.jpg";
String url2 = IDN.toUnicode(url);
BufferedImage bi = ImageIO.read(new URL(url2));
System.out.println(bi);
Run Code Online (Sandbox Code Playgroud)

此代码始终失败

javax.imageio.IIOException:无法从URL获取输入流!
引起:java.net.UnknownHostException:见.香港

我究竟做错了什么?

Jon*_*lly 5

仅对URL的主机部分进行编码,并确保使用IDN.toASCII()而不是IDN.toUnicode()

String fullUrl = "http://?.??/images/wonton.jpg";
URL url = new URL(fullUrl);

url.getProtocol(); // "http"
url.getHost(); // "?.??"
url.getPath(); // "/images/wonton.jpg"

String asciiHost = IDN.toASCII(url.getHost());
String validUrl = url.getProtocol() + "://" + asciiHost + url.getPath();
System.out.println(validUrl);
BufferedImage bi = ImageIO.read(new URL(validUrl));
Run Code Online (Sandbox Code Playgroud)

控制台输出: http://xn--nw2a.xn--j6w193g/images/wonton.jpg

请注意,如果要包含空格等字符,则可能需要URLEncode URI的资源部分.