第二次访问从 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());
}
最佳答案
一旦您阅读了流,您就已经阅读了流。如果不调用 mark()
和 reset()
方法以及 InputStream
的实现,您不能多次重新读取流您正在使用的类应该首先支持这一点。
除此之外:
- 您的 try-catch 语句需要:
- 要捕获适当的异常,而不仅仅是抛出
Exception
,而是 --IOException
、URLException
或任何相关的(您的 IDE 将如果您删除catch (Exception e)
block ,建议/修复此问题。 finally
block 检查流是否不为空并关闭它们。
- 要捕获适当的异常,而不仅仅是抛出
- 您的方法应该抛出 IOException。
关于java - 第二次访问 -> 从 URLConnection getInputStream() 时出现 504 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15134359/