gpt4 book ai didi

c - C 中的 HTTP 请求语法

转载 作者:可可西里 更新时间:2023-11-01 16:43:37 25 4
gpt4 key购买 nike

我正在使用以下代码将一个简单的网页复制到“缓冲区”。

char sendBuffer[256];
ZeroMemory(sendBuffer, 256);
strcpy(sendBuffer, "HTTP/1.1 403 Forbidden\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE html>\r\n<html>\r\n\t<head>\r\n\t\t<title>403 - Forbidden</title>\r\n\t</head>\r\n\t<body>\r\n\t\t<h1>403 - Forbidden</h1>\r\n\t</body>\r\n</html>");

这在 Firefox 中有效,但是 Chrome 有点崩溃。

我正在使用\r\n 作为我被告知要使用的“CRLF”,这是正确的吗?

最佳答案

您缺少 Content-Length header 。如果您包含 Connection: close 作为 header 以指示连接的关闭将标志着内容的结束,则没有必要这样做。

const char msg[] =
"HTTP/1.1 403 Forbidden\r\n"
"Connection: close\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"<!DOCTYPE html>\r\n"
"<html>\r\n"
"\t<head>\r\n"
"\t\t<title>403 - Forbidden</title>\r\n"
"\t</head>\r\n"
"\t<body>\r\n"
"\t\t<h1>403 - Forbidden</h1>\r\n"
"\t</body>\r\n</html>"
;

char sendBuffer[256];
snprintf(sendBuffer, sizeof(sendBuffer), "%s", msg);

否则,您将不得不动态或静态地将消息正文长度插入到 Content-Length header 中。

const char msg_header[] =
"HTTP/1.1 403 Forbidden\r\n"
"Content-Length: %d\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"%s"
;

const char msg_body[] =
"<!DOCTYPE html>\r\n"
"<html>\r\n"
"\t<head>\r\n"
"\t\t<title>403 - Forbidden</title>\r\n"
"\t</head>\r\n"
"\t<body>\r\n"
"\t\t<h1>403 - Forbidden</h1>\r\n"
"\t</body>\r\n</html>"
;

char sendBuffer[256];
snprintf(sendBuffer, sizeof(sendBuffer), msg_header,
sizeof(msg_body)-1, msg_body);

正如 Eddy_Em 所指出的,如果服务器确实关闭了连接,则无需声明 Connection: close。如果您的服务器在发出此消息后未关闭连接,则需要内容长度。

关于c - C 中的 HTTP 请求语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com