我正在尝试从 url 下载图像,但得到 java.io.IOException: 异常。
我的代码是:

    public static void main(String[] args) throws MalformedURLException, IOException {

    File picutreFile = new File("test.jpg");
    FileUtils.copyURLToFile(new java.net.URL("http://paceoil.ca/files/includes/images/images-stories-presentation-october-icon-graphic.jpg"), picutreFile);

}

运行时抛出:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://paceoil.ca/files/includes/images/images-stories-presentation-october-icon-graphic.jpg
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1460)
at com.hrant.Test.main(Test.java:14)

此代码适用于某些网址,但为此我不明白为什么不这样做。
提前非常感谢。

最佳答案

尝试在您的 url 上设置用户代理属性,例如,看看它是否有帮助:

File picutreFile = new File("src/test.jpg");
         URL url=new URL("http://paceoil.ca/files/includes/images/images-stories-presentation-october-icon-graphic.jpg");
         URLConnection conn = url.openConnection();
         conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
         conn.connect();
            FileUtils.copyInputStreamToFile(conn.getInputStream(), picutreFile);

关于java - 无法下载图片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25630202/

10-10 15:34