2016-01-06 35 views
2
拿到StackOverflow上的天賦圖像

我已經在我的程序編寫下面的代碼獲得403試圖用的ImageIO

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

我收到以下錯誤

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

我可以使用wget的圖像時,由在瀏覽器上寫網址等...
我不明白爲什麼我在這裏得到403。

+0

來看一下,http://stackoverflow.com/questions/3023243/unable-to-acquire-image-through-imageio-readurl-because-of- connection-timed-ou可能會幫你 – Zia

回答

2

它可以在這個網址檢查,如用戶代理財產可能的服務器,讓你得到403錯誤,

注:僅通過設置空白的User-Agent 屬性在這種情況下,其工作

試試這個代碼

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(); 
} 
+1

那麼,我是老實人,並不想騙我是Mozilla的服務器,而不是java應用程序。 ;) – afzalex

+1

剛剛離開那個屬性空白,它也將在這種情況下工作:) –

+0

是的,它也在工作,你剛剛救了我從成爲一個小人。 BTY奇怪的是,服務器給我錯誤,因爲我沒有提供一個標題,並沒有給任何,如果我只是提供空值的標題。 – afzalex