gpt4 book ai didi

java - 尝试使用 ImageIO 获取 StackOverflow 的 flair 图像时出现 403

转载 作者:行者123 更新时间:2023-11-30 08:42:14 24 4
gpt4 key购买 nike

我在我的程序中写了下面的代码

url = new URL("http://stackoverflow.com/users/flair/3626698.png?theme=dark");
ImageIO.read(url);

出现以下错误

Exception in thread "main" javax.imageio.IIOException: Can't get input stream from URL!
at javax.imageio.ImageIO.read(ImageIO.java:1395)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:25)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://stackoverflow.com/users/flair/3626698.png?theme=dark
....

我可以使用 wget 获取图像,通过在浏览器上写入 url 等...
我不明白为什么我在这里得到 403。

最佳答案

此 url 上的服务器可能会检查用户代理等属性,因此您会收到 403 错误,

note : in this case its working by just setting blank User-Agent property

试试这段代码

try {
URL url = new URL("http://stackoverflow.com/users/flair/3626698.png?theme=dark");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "");
BufferedImage image = ImageIO.read(httpcon.getInputStream());
File outputfile = new File("image.jpg");
ImageIO.write(image, "jpg", outputfile);
}
catch (Exception e) {
e.printStackTrace();
}

关于java - 尝试使用 ImageIO 获取 StackOverflow 的 flair 图像时出现 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632407/

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