如何在 C++ 中解析 http 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15179409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to parse http request in c++
提问by John Smith
I'm trying to write a small c++ webserver which handles GET, POST, HEAD requests. My problem is I don't know how to parse the headers, message body, etc. It's listening on the socket, I can even write stuff out to the browser just fine, but I'm curious how should I do this in c++.
我正在尝试编写一个处理 GET、POST、HEAD 请求的小型 C++ 网络服务器。我的问题是我不知道如何解析标题、消息正文等。它正在侦听套接字,我什至可以将内容写到浏览器中就好了,但我很好奇我应该如何在 C++ 中做到这一点。
Afaik a standard GET/POST request should look something like this:
Afaik 一个标准的 GET/POST 请求应该是这样的:
GET /index HTTP/1.1
Host: 192.168.0.199:80
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
this is the message body
All lines ended with '\r\n'.
所有行都以 '\r\n' 结尾。
Should I just split the request at '\n' and trim them (and if so how)? Also how to handle files in post data?
我应该在 '\n' 处拆分请求并修剪它们(如果是这样,如何修剪)?另外如何处理发布数据中的文件?
Main thing I want to achieve is to get a vector containing headers key=>value pairs, a string with request method, the post data (like in PHP, if it's present), and the query string (/index for example) as string or vector splitted by '/'.
我想要实现的主要目标是获取一个包含标头 key=>value 对的向量、一个带有请求方法的字符串、post 数据(如在 PHP 中,如果存在)和查询字符串(例如 /index)作为字符串或由'/'分割的向量。
Thanks!
谢谢!
采纳答案by masoud
Before doing everything yourself, I introduce you Poco:
在自己做所有事情之前,我向您介绍Poco:
class MyHTTPRequestHandler : public HTTPRequestHandler
{
public:
virtual void handleRequest(HTTPServerRequest & request,
HTTPServerResponse & response) {
// Write your HTML response in res object
}
};
class MyRequestHandlerFactory : public HTTPRequestHandlerFactory
{
MyHTTPRequestHandler handler;
public:
MyRequestHandlerFactory(){}
HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request)
{
const string method = request.getMethod();
if (method == "get" || method == "post")
return &handler;
return 0;
}
};
int main()
{
HTTPServerParams params;
params.setMaxQueued(100);
params.setMaxThreads(16);
ServerSocket svs(80);
MyRequestHandlerFactory factory;
HTTPServer srv(&factory, svs, ¶ms);
srv.start();
while (true)
Thread::sleep(1000);
}
回答by Konrad Rudolph
Boost.Asio is a good library but relativel low-level. You'll really want to use a higher level library. There's a modern C++ library called node.nativewhich you should check out. A very server can be implemented as follows:
Boost.Asio 是一个很好的库,但相对低级。您真的很想使用更高级别的库。您应该查看一个名为node.native的现代 C++ 库。一个非常服务器可以实现如下:
#include <iostream>
#include <native/native.h>
using namespace native::http;
int main() {
http server;
if(!server.listen("0.0.0.0", 8080, [](request& req, response& res) {
res.set_status(200);
res.set_header("Content-Type", "text/plain");
res.end("C++ FTW\n");
})) return 1; // Failed to run server.
std::cout << "Server running at http://0.0.0.0:8080/" << std::endl;
return native::run();
}
It doesn't get much simpler than this.
没有比这更简单的了。
回答by firebush
回答by Ferenc Deak
Yes, this is basically just string parsing and then the response creating that goes back to the browser, following the specification.
是的,这基本上只是字符串解析,然后按照规范创建返回到浏览器的响应。
But if this is not just an hobby project and you do not want to take on a really big task you should use either Apache, if you need a web server you need to extend, or tntnet, if you need a c++ web framework, or cpp-netlibif you need C++ network stuff.
但是,如果这不仅仅是一个爱好项目,并且您不想承担真正的大任务,那么您应该使用 Apache(如果您需要扩展的 Web 服务器)或tntnet(如果您需要 C++ Web 框架),或者cpp-netlib如果你需要 C++ 网络的东西。