http知識(shí)與技巧
首先客戶端發(fā)送REQUEST, 服務(wù)端收到后發(fā)回RESPONSE, 完成一次HTTP請求
-
REQUEST一般用GET或者POST類型
- GET類型不包含body塊, 可以在url上向服務(wù)器發(fā)送信息
- POST類型包含body塊, 可以利用它向服務(wù)器發(fā)送大量信息
測試http請求可以使用curl命令
# 使用curl發(fā)送POST請求到服務(wù)端的命令
# -X 請求是POST請求
# -H 指明了body是json格式
# -d 包含body內(nèi)容
# 127.0.0.1:8001 本機(jī)IP地址以及服務(wù)器監(jiān)聽的端口
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) {}
//當(dāng)客戶端發(fā)送http請求后, 服務(wù)端
void handleRequest(HTTPServerRequest &req, HTTPServerResponse &res) override {
Application &app = Application::instance();
std::ostream &ostr = res.send();
res.setChunkedTransferEncoding(true);
res.setContentType("text/html");
//返回給客戶端的內(nèi)容
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>";
//打印從客戶端發(fā)來的信息
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 {
//如何回復(fù)http請求
return new TimeRequestHandler(req.getURI());
}
};
class HTTPTimeServer : public ServerApplication {
protected:
int main(const std::vector<std::string> &args) override {
ServerSocket svs(SERVER_PORT);
//設(shè)置了服務(wù)器監(jiān)聽的端口, 設(shè)置了http的請求發(fā)送到服務(wù)器的時(shí)候
//應(yīng)該如何處理 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);
}