HTTP协议:消息正文的结尾 [英] HTTP protocol: end of a message body

查看:284
本文介绍了HTTP协议:消息正文的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个解析标头的程序,我想在接收到POST的情况下阅读消息正文.

I built a program that parses the header and I would like to read the message body in case I receive a POST.

对于标题,我已经能够确定标题何时结束.我的邮件正文有更多问题.我是否应该查看"Content-Length"字段以了解何时停止读取输入?在我当前的代码中(如下所示),直到我在Firefox中点击红叉(停止加载页面)后,它才会停止.

For headers, I have been able to look for to determine when the header ends. I am having more issues for the message body. Am I supposed to look at "Content-Length" field to know when to stop reading input? In my current code (below), it will not stop until I hit the red cross (stop loading page) in Firefox.

这是代码:

size_t n;
unsigned char newChar;

int index = 0;
int capacity = 50;
char *option = (char *) malloc(sizeof(char) * capacity); 

while ( ( n = read( req->socket, &newChar, sizeof(newChar) ) ) > 0 ) {
  if (newChar == '\0' || newChar == '\n') break; // This is not working

  if (index == capacity) {
    capacity *= 2;
    option = (char *) realloc(option, sizeof(char) * capacity);
    assert(option != NULL);
  }
  option[index++] = newChar;
  fprintf(stderr, "%c", newChar);
}

if (index == capacity) {
  capacity *= 2;
  option = (char *) realloc(option, sizeof(char) * capacity);
  assert(option != NULL);
}
option[index] = '\0';

打印出正确的输入,但是我想知道为什么直到按下停止加载按钮时它才会停止.我想知道是否还有其他解决方案,或者是否需要使用标题中的"Content-Length"字段.

The correct input gets printed, but I wonder why it won't stop until the stop loading button get pressed. I'd like to know if there is any other solution or if I please need to use the "Content-Length" field in the header.

非常感谢您,

一月

推荐答案

需要考虑一些事项.您可能需要考虑如何处理所有这些情况?

There are a few things to consider. You'll want to consider how you want to handle all of these cases perhaps?

  • 对于HTTP协议1.0,使用连接关闭来表示数据结束.

  • For HTTP protocol 1.0 the connection closing was used to signal the end of data.

在HTTP 1.1中进行了改进,它支持持久连接.通常,对于HTTP 1.1,您可以设置或读取Content-Length标头,以了解需要多少数据.

This was improved in HTTP 1.1 which supports persistant connections. For HTTP 1.1 typically you set or read the Content-Length header to know how much data to expect.

最后,使用HTTP 1.1时,也可能会出现"Chunked"模式,您将获得它们的大小,并且当找到一个块Size == 0时,您知道已经到了末尾.

Finally with HTTP 1.1 there is also the possibility of "Chunked" mode, you get the size as they come and you know you've reached the end when a chunk Size == 0 is found.

您还了解 libcurl 吗?它肯定会帮助您重新安装轮子.

Also do you know about libcurl? It will certainly help you having to re-implement the wheel.

这篇关于HTTP协议:消息正文的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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