3

I have written following code in my program

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

I am getting following error

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
....

I can get an image using wget, by writing url on browser etc...
I don't understand why I am getting 403 here.

afzalex
  • 8,598
  • 2
  • 34
  • 61
  • look in to http://stackoverflow.com/questions/3023243/unable-to-acquire-image-through-imageio-readurl-because-of-connection-timed-ou may be it will help you – Zia Jan 06 '16 at 11:56

1 Answers1

3

it may possible server at this url checks for property like user agent,so you are getting 403 error,

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

Try this code

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();
 }
Keval
  • 1,857
  • 16
  • 26
  • 1
    Well, I am honest person and didn't wanted to lie server that I am Mozilla, not java application. ;) – afzalex Jan 06 '16 at 12:11
  • 1
    just left that property blank , it will also work in this case :) – Keval Jan 06 '16 at 12:13
  • Yeah, it is also working, You just saved me from being a lier. BTY It is strange that server is giving me error because I didn't provided a header, and is not giving any if I just provide header with blank value. – afzalex Jan 06 '16 at 12:33