Java - unable to download image from internet if src has hyphen

I have a program that involves downloading an image from the internet from a specified src image and it works fine in most cases, however if the image src has a "-" in the address, I get an IOException.

BufferedImage image = null;
fileName = emailFirst + "_at_" + emailLast + " (" + fullName + ")";

URL url = new URL(imageUrl);
image = ImageIO.read(url);

System.out.println("DIRECTORY: " + directory);
ImageIO.write(image, "jpg", new java.io.File(directory + "\\" + fileName + ".jpg"));

      

The only cases where it doesn't work is if the url has a hyphen like this link in "wp-content"

https://www.applicoinc.com/wp-content/uploads/2016/04/Employee_Alex_Moazed.jpg

Any ideas?

+3


source to share


1 answer


If you look at the documentation for the class URL

, you will see this (emphasis mine)

The URL class does not itself encode or decode any URL components according to the escaping mechanism defined in RFC2396. The responder must encode any fields that need to be escaped prior to calling the URL, and also decode any escaped fields that are returned from the URL.



To encode it correctly, you must initialize URI

with your url string and call a toURL

method to get the encoded url.

+2


source







All Articles