Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Couldn't download image

Tags:

java

I'm trying to download images from url but got java.io.IOException: exception. My code is:

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

}

When run threw :

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)

This code works for some urls but for this I couldnt understand why not. Advance many Thanks.

like image 818
Hrant Vardanyan Avatar asked Dec 26 '22 04:12

Hrant Vardanyan


1 Answers

try setting user agent property on your url, for example, see if it helps:

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);
like image 190
user3487063 Avatar answered Dec 28 '22 05:12

user3487063