Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 403 when trying to get StackOverflow's flair image with ImageIO

Tags:

java

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.

like image 508
afzalex Avatar asked Dec 28 '25 18:12

afzalex


1 Answers

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();
 }
like image 86
Keval Avatar answered Dec 31 '25 11:12

Keval



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!