I am downloading image from link with the help of this code in java
public static BufferedImage ImageDownloader(String urlString){
BufferedImage image = null;
try {
URL url = new URL(urlString.replace(" ","%20"));
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();
InputStream inputStream = connection.getInputStream();
image = ImageIO.read(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
above code is downloading images perfectly but it is not able to download images with link like this
I understand that I can remove that query parameter and update url, but is there any better solution than this?
Just don't set the user agent:
public static BufferedImage ImageDownloader(String urlString){
BufferedImage image = null;
try {
String cleanUrl = urlString.replace(" ","%20");
URL url = new URL(cleanUrl);
URLConnection connection = url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
image = ImageIO.read(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
Alternatively:
public static BufferedImage ImageDownloader(String urlString){
BufferedImage image = null;
try {
String cleanUrl = urlString.replace(" ","%20");
URL url = new URL(cleanUrl);
image = ImageIO.read(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
Or also:
public static BufferedImage ImageDownloader(String urlString){
BufferedImage image = null;
try {
URL url = new URL(urlString.replace(" ","%20"));
image = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}