yousuf iqbal
yousuf iqbal

Reputation: 438

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?

Upvotes: 4

Views: 811

Answers (2)

cdr89
cdr89

Reputation: 986

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

Upvotes: 1

Suhas Bachhav
Suhas Bachhav

Reputation: 423

use transferFrom()

URL website = new URL("http://www.example.com/example.php");
ReadableByteChannel RB = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("example.html");
fos.getChannel().transferFrom(RB, 0, Long.MAX_VALUE);

Upvotes: 0

Related Questions