在JAVA中从带有查询参数的链接下载图像

时间:2018-06-21 09:08:46

标签: java image urlconnection

我正在使用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;
}

以上代码可完美下载图像,但无法下载具有此类链接的图像

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

我知道我可以删除该查询参数并更新url,但是还有什么更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

只需不设置用户代理:

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

或者:

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

或者:

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

答案 1 :(得分:0)

使用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);