使用字符串形成 HTTP 响应
Forming a HTTP response with strings
我正在开发带有boost的HTTP服务器,我对形成HTTP响应有一些疑问,尤其是标头。
以下是组装 GET 响应的代码:
std::string h = statusCodes[200]; // The status code is already finished with a 'rn'
std::string t = "Date: " + daytime_() + "rn";
std::string s = "Server: Muffin 1.0rn";
std::string content = search->second();
std::string type = "Content-Type: text/htmlrn";
std::string length = "Content-Length: " + std::to_string(content.size()) + "rn";
res = h + t + s + length + type + "rn" + content + "rn";
正如他们在这个网站上所说的那样,这是标题规范:
请求和响应消息的格式相似,并且 以英语为导向。这两种消息都包含:
- 首行,零行或多个标题行,
- 一个空行(即 CRLF 本身),
- 和可选的消息正文(例如文件、查询数据或查询输出)。
但是当我在服务器上执行请求时,只有日期在标题中,其余的直接在内容中
HTTP/1.1 200 OK // Header
Date: Tue May 24 10:28:58 2016 // Header
Server: Muffin 1.0 // Content
Content-Length: 31
Content-Type: text/html
This is supposed to be an ID
我不知道这有什么问题,这是我第一次处理HTTP响应。
感谢您的帮助
我终于找到了这个错误。
我的白天函数返回一个带有换行符的字符串。
这是原始函数,它使用折旧 ctime
std::string
Response::daytime_()
{
std::time_t now = std::time(0);
return std::ctime(&now);
}
现在带有 strftime 的新功能
std::string
Response::daytime_()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,80,"%a %b %d %H:%M:%S %Y",timeinfo);
std::string time(buffer);
return time;
}
以及形成响应的新方法,仅使用""
std::string res = "";
std::string h = statusCodes[200];
std::string t = "Date: " + daytime_() + "rn";
std::string s = "Server: Muffin 1.0rn";
std::string content = search->second();
std::string type = "Content-Type: text/htmlrn";
std::string length = "Content-Length: " + std::to_string(content.size()) + "rn";
res = h + t + s + length + type + "n" + content + "rn";
相关文章:
- HTTP 响应格式不正确?
- 使用 WinInet 修改/删除 HTTP 响应标头
- 如何在C++中使用 Curl 获取 HTTP 响应字符串
- QNetworkReply 如果 HTTP 响应类型为 201 CREATED,则返回空响应
- 如何从 HTTP 响应中删除垃圾数据
- 如何存储 http 响应并发送到浏览器
- Boost BEAST操纵HTTP响应标头持续接受
- 使用套接字编程的怪异HTTP响应
- C 从HTTP响应中获取图片
- HTTP响应标头是否可以不以状态行开头
- 使用字符串形成 HTTP 响应
- Webkit GTK:获取HTTP响应
- Recv 未返回足够的字节(二进制 http 响应)
- 无法接收HTTP响应正文C++
- 通过套接字正确发送 HTTP 响应
- 损坏的HTML - 浏览器不会从我的网络服务器下载整个HTTP响应,CURL可以
- 我如何从QNetworkReply读取内容(http响应体)
- NSMutableData to NSString -如何知道HTTP响应使用哪种编码
- 支持http 1.1响应缓存的c++库
- HTTP响应连接重置