Failed to download picture

I am trying to load images from url but got java.io.IOException: exception. My code:

    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 you run throw:

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 that I couldn't figure out why not. Many thanks.

+1


source to share


3 answers


try setting the user agent property to 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);

      

+6


source


Just a suggestion:

If this only happens to that URL (or Domain), it is possible that the http server implementation on the other end checks some HTTP headers before processing the request. And you are not submitting such information.

The result may be that the server will respond with a 403.



Can be: Forbidden to unknown client (e.g. User-Agent)

Perhaps this link will help add headers to your request:
fooobar.com/questions/44094 / ...

0


source


this server may not promise any request with invalid HTTP request. you can send your HTTP header with the request and the server will promise you to download this image if it needs HTTP header information. something like that:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredent = "username:password";
myURLConnection.setRequestProperty ("property", value);
myURLConnection.setRequestMethod("POST");

      

0


source







All Articles