http知识与技巧
首先客户端发送REQUEST, 服务端收到后发回RESPONSE, 完成一次HTTP请求
-
REQUEST一般用GET或者POST类型
- GET类型不包含body块, 可以在url上向服务器发送信息
- POST类型包含body块, 可以利用它向服务器发送大量信息
测试http请求可以使用curl命令
# 使用curl发送POST请求到服务端的命令
# -X 请求是POST请求
# -H 指明了body是json格式
# -d 包含body内容
# 127.0.0.1:8001 本机IP地址以及服务器监听的端口
curl -X POST -H "Content-Type: application/json" -d '"{"key": "value"}"' 127.0.0.1:8001
源码与编译
编译命令
g++ main.cpp -l PocoJSON -l PocoFoundation -l PocoNet -l PocoUtil
main.cpp
#include <iostream>
#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPRequestHandlerFactory.h>
#include <Poco/Net/HTTPServer.h>
#include <Poco/Net/HTTPServerParams.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Net/ServerSocket.h>
#include <Poco/Util/ServerApplication.h>
#include <Poco/StreamCopier.h>
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerParams;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::ServerSocket;
using Poco::Util::Application;
using Poco::Util::ServerApplication;
#define SERVER_PORT 8001
class TimeRequestHandler : public HTTPRequestHandler {
private:
std::string _str;
public:
TimeRequestHandler(std::string str): _str(str) {}
//当客户端发送http请求后, 服务端
void handleRequest(HTTPServerRequest &req, HTTPServerResponse &res) override {
Application &app = Application::instance();
std::ostream &ostr = res.send();
res.setChunkedTransferEncoding(true);
res.setContentType("text/html");
//返回给客户端的内容
ostr << "<html><head><title>HTTPTimeServer powered by "
"POCO C++ Libraries</title>";
ostr << "<body><p style=\"text-align: center; "
"font-size: 48px;\">";
ostr << req.clientAddress().toString();
ostr << "</p></body></html>";
//打印从客户端发来的信息
std::string recv_string;
Poco::StreamCopier::copyToString(req.stream(), recv_string);
std::cout << _str << "-data-"<< recv_string << std::endl;
}
};
class TimeRequestHandlerFactory : public HTTPRequestHandlerFactory {
public:
TimeRequestHandlerFactory() {}
HTTPRequestHandler *
createRequestHandler(const HTTPServerRequest &req) override {
//如何回复http请求
return new TimeRequestHandler(req.getURI());
}
};
class HTTPTimeServer : public ServerApplication {
protected:
int main(const std::vector<std::string> &args) override {
ServerSocket svs(SERVER_PORT);
//设置了服务器监听的端口, 设置了http的请求发送到服务器的时候
//应该如何处理 TimeRequestHandlerFactory
HTTPServer srv(new TimeRequestHandlerFactory(), svs,
new HTTPServerParams);
srv.start();
waitForTerminationRequest();
srv.stop();
return Application::EXIT_OK;
}
};
int main(int argc, char **argv) {
HTTPTimeServer app;
return app.run(argc, argv);
}