gpt4 book ai didi

java - 从带有 JAVA 查询参数的链接下载图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:15 25 4
gpt4 key购买 nike

我正在借助 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,但是还有比这更好的解决方案吗?

最佳答案

只是不要设置用户代理:

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

关于java - 从带有 JAVA 查询参数的链接下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50964668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com