流式传输Http请求的主体时如何处理错误 [英] What to do with errors when streaming the body of an Http request

查看:294
本文介绍了流式传输Http请求的主体时如何处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Http消息中处理服务器错误?

How do I handle a server error in the middle of an Http message?

假设我已经发送了消息的标题,我正在流式传输
消息的正文,当我遇到意外错误时该怎么办。

Assuming I already sent the header of the message and I am streaming the the body of the message, what do I do when I encounter an unexpected error.

我也假设这个错误是在生成内容而不是连接错误时引起的。

I am also assuming this error was caused while generating the content and not a connection error.

(非常)简化代码:

// I can define any transfer encoding or header fields i need to.
send(header);  // Sends the header to the Http client.

// Using an iterable instead of stream for code simplicity's sake.
Iterable<String> stream = getBodyStream();
Iterator<String> iterator = stream.iterator();

while (iterator.hasNext()) {
    String string;
    try {
       string = iterator.next();   
    catch (Throwable error) { // Oops! an error generating the content.
        // What do i do here? (In regards to the Http protocol)
    }

    send(string);
}

有没有办法告诉客户端服务器出现故障,应该重试还是放弃连接还是放弃连接?

Is there a way to tell the client the server failed and should either retry or abandon the connection or am I sool?

代码大大简化了,但我只询问协议而不是确切的代码。

The code is greatly simplified but I am only asking in regards to the protocol and not the exact code.

谢谢

推荐答案

以下其中一项应该这样做:

One of the following should do it:


  1. 关闭连接(重置或正常关闭)

  2. 写一个格式错误的块(并关闭连接),这将触发客户端错误

  3. 添加 http预告片你的客户出了什么问题。

  4. 更改你的更高级协议。您发送的最后一段数据是散列或长度,客户端知道要处理它。

  5. 如果您可以生成散列或长度(如果使用http块,则在自定义标头中) )在您开始发送之前,您的内容可以在标题中发送,以便您的客户知道会发生什么。

  1. Close the connection (reset or normal close)
  2. Write a malformed chunk (and close the connection) which will trigger client error
  3. Add a http trailer telling your client that something went wrong.
  4. Change your higher level protocol. Last piece of data you send is a hash or a length and the client knows to deal with it.
  5. If you can generate a hash or a length (in a custom header if using http chunks) of your content before you start sending you can send it in a header so your client knows what to expect.

这取决于什么您希望您的客户处理数据(保留或丢弃它)。您可能无法在客户端进行更改,因此最后一个选项不起作用。

It depends on what you want your client to do with the data (keep it or throw it away). You may not be able to make changes on the client side so the last option will not work for example.

以下是关于不同关闭方式的一些解释。 TCP选项SO_LINGER(零) - 何时需要。查看最高计数而非接受答案的答案。

Here is some explanation about the different ways to close. TCP option SO_LINGER (zero) - when it's required. Look at the answer with the highest count not the accepted one.

这篇关于流式传输Http请求的主体时如何处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆