【问题标题】:Accessing second time -> 504 exception while getInputStream() from URLConnection从 URLConnection 的 getInputStream() 访问第二次 - > 504 异常
【发布时间】:2013-02-28 11:28:09
【问题描述】:

第二次访问从 URLConnection 获取输入流时出现 504 异常。当我在访问特定的 url 时重新启动我的系统时,它运行良好,但是在第二次访问时它会引发错误。

注意:

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

【问题讨论】:

    标签: java jsp url httpurlconnection


    【解决方案1】:

    一旦您阅读了流,您就已经阅读了流。如果不调用 mark()reset() 方法,则不能多次重新读取流,并且您使用的 InputStream 类的实现实际上应该首先支持这一点。

    除此之外:

    • 您的 try-catch 语句需要:
      • 捕获正确的异常,而不仅仅是抛出Exception,而是--IOExceptionURLException 或任何相关的(如果您删除catch (Exception e) 块,您的IDE 将为您推荐/修复此问题)。
      • finally 块检查流是否不为空并关闭它们。
    • 您的方法应该引发 IOException。

    【讨论】:

      【解决方案2】:

      也许您没有以正确的方式关闭输入流或输出流。 始终使用

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

      【讨论】:

      • 对于调试:不要使用 catch(Exception e),因为您无法确定抛出了哪个异常,请单独捕获所有异常。
      • 此外,使用“catch(Exception e)”是不行的,它是一个市长异常处理反模式(谷歌用于未经检查的异常),永远不应该这样使用!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多