2013-02-28 68 views
1

訪問第二次從URLConnection獲取輸入流時發生504異常。當我的系統重新啓動時,即時通訊訪問特定的網址它的工作,但第二次訪問時,它會引發錯誤。訪問第二次 - > 504異常,而來自URLConnection的getInputStream()

注:

Using Tomcat 6, Java, JSP 

代碼波紋管:

OutputStream outStream = null; 
    URLConnection uCon = null; 

    InputStream is = null; 
    try { 
     URL Url; 
     byte[] buf; 
     int ByteRead, ByteWritten = 0; 
     Url = new URL("www.sample.com/download/file.xml"); 
     outStream = new BufferedOutputStream(new FileOutputStream("/home/temp/myfile.xml")); 

     uCon = Url.openConnection(); 
     is = uCon.getInputStream(); 
     buf = new byte[size]; 
     while ((ByteRead = is.read(buf)) != -1) { 
      outStream.write(buf, 0, ByteRead); 
      ByteWritten += ByteRead; 
     } 
     System.out.println("Downloaded Successfully."); 
     is.close(); 
     outStream.close(); 
    } catch (Exception e) { 
     System.out.println("Required File is not there "+e.getMessage());    
    } 

回答

3

一旦你讀過流,你讀過流。您不能重複讀取數據流,而不會調用mark()reset()方法,並且您正在使用的InputStream類的實現應該首先支持這一點。

除了:

  • 你的try-catch語句需要:
    • 趕上正確的異常,而不是隨便扔Exception,而是 - IOExceptionURLException,或其他的相關(您的IDE將爲你推薦/解決這個問題,如果你刪除catch (Exception e)塊)。
    • A finally塊檢查流是否不爲空並關閉它們。
  • 你的方法應該拋出一個IOException。
0

也許你不關閉你的InputStream和OutputStream的你在正確的道路。 始終使用

finally { 
    is.close(); 
    outputStream.close() 
} 
+2

並且用於調試:不要使用catch(Exception e),因爲您無法確定拋出了哪個異常,單獨捕獲所有異常。 – puchmu 2013-02-28 11:45:24

+2

此外,使用「catch(Exception e)」是一個禁止使用,它是一個市長異常處理反模式(谷歌未經檢查的例外),不應該像這樣使用! – puchmu 2013-02-28 13:07:49

相關問題