Get image from url using kanji

I want to get an image from a remote URL.

String url =  "http://見.香港/images/wonton.jpg";
String url2 = IDN.toUnicode(url);
BufferedImage bi = ImageIO.read(new URL(url2));
System.out.println(bi);

This code always fails with

javax.imageio.IIOException: Unable to get input from URL!
Called: java.net.UnknownHostException: 見. 香港

What am I doing wrong?

+4
source share
1 answer

Encode only part of the host URL and make sure you use IDN.toASCII(), notIDN.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));

Console output: http: //xn--nw2a.xn--j6w193g/images/wonton.jpg

Note that you may need to use the URLEncode part of a URI resource if it should contain characters such as spaces.

+5
source

Source: https://habr.com/ru/post/1691622/


All Articles