Search code examples
javaimageurlconnection

Download image from link with query parameter in JAVA


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

https://cdn7.bigcommerce.com/s-ca9dp6b/products/1468/images/7652/71D1kb88oCL._SL1500___27837.1494844084.500.750.jpg?c=2

I understand that I can remove that query parameter and update url, but is there any better solution than this?


Solution

  • 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;
    }