java - 写入输出流处理过程中出错

标签 java http error-handling fileinputstream

我正在构建一个 httpserver 作为我学术 java 类(class)的一部分, 服务器应该只支持基本的 GET 和 POST 请求。

我想知道是否有一种优雅的方法来处理将 html 文件流内容(以及在我已经发送响应 header 之后)写入 HttpServer 输出的中间错误流。

通过优雅的方式,我指的是向用户显示或重定向到“内部服务器错误”错误页面。

我尝试重新发送带有 501 错误代码的 http 响应 header ,但 java 抛出一个异常,声称 header 已发送...

一个解决方法是将文件的内容读入内存,然后才发送标题和内容,但可能会出现其他问题,而且,我不想在发送之前将大文件加载到内存中作为回应。

最佳答案

一旦在线路上发送了响应状态,就无法更改。因此,如果您发送了 200 OK 响应,您之后就无法改变主意。如您所见,这会在响应中出现错误时出现问题。

据我所知,您唯一能做的就是发送分块响应。请参阅 RFC 2616 的第 3.6.1 节:

The chunked encoding modifies the body of a message in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer containing entity-header fields. This allows dynamically produced content to be transferred along with the information necessary for the recipient to verify that it has received the full message.

这个预告片的目的是给出关于实体主体的信息,这些信息在实体主体发送之前是无法计算的。但是,第 7.1 节允许在此预告片中包含任何 header :

The extension-header mechanism allows additional entity-header fields to be defined without changing the protocol, but these fields cannot be assumed to be recognizable by the recipient. Unrecognized header fields SHOULD be ignored by the recipient and MUST be forwarded by transparent proxies.

因此,虽然您可以在响应中发出错误信号,但必须在这两个部分之间约定如何发出信号。通常,您不能使用任何您认为客户会理解为发出错误情况信号的方法。

在带有 Content-length header 的消息中提前结束连接是一种选择,但被明确禁止:

When a Content-Length is given in a message where a message-body is allowed, its field value MUST exactly match the number of OCTETs in the message-body. HTTP/1.1 user agents MUST notify the user when an invalid length is received and detected.

也就是说,虽然服务器发送的消息不能短于他宣传的长度,但客户端必须检查此错误情况并据此报告(代理甚至可以缓存此部分响应)。

关于java - 写入输出流处理过程中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7091211/

相关文章:

java - 如何在 Java 中将函数作为参数传递给 Callable

java - 如何刷新 NetBeans 中的自定义 bean?

java - 将外部列添加到 JPA 映射的表会破坏正常运行吗?

REST PUT 与 POST 与 UUID

http - URL "scheme plus authority"的正式名称

c# - 在类和 GUI 周围移动数据

asp-classic - 如何正确报告/处理经典的 asp 页面错误和数据库错误

java - 如何为这样的表结构创建 DAO/模型

javascript - HTTP 内容类型 header 和 JSON

javascript - 在对象内调用对象方法——错误: cannot read property of undefined