本文整理汇总了C++中poco::net::HTTPServerRequest类的典型用法代码示例。如果您正苦于以下问题:C++ HTTPServerRequest类的具体用法?C++ HTTPServerRequest怎么用?C++ HTTPServerRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HTTPServerRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: EachNodeValue
void EachNodeValue(Poco::Net::HTTPServerRequest &request, const F &f)
{
if(!request.hasContentLength() || request.getContentLength()>1024*4) {
return;
}
size_t size = (size_t)request.getContentLength();
std::istream& stream = request.stream();
std::string encoded_content;
std::string content;
encoded_content.resize(size);
stream.read(&encoded_content[0], size);
Poco::URI::decode(encoded_content, content);
std::regex reg("(\\d+)");
std::cmatch m;
size_t pos = 0;
for(;;) {
if(std::regex_search(content.c_str()+pos, m, reg)) {
f(m[1].str().c_str());
pos += m.position()+m.length();
}
else {
break;
}
}
}
示例2: handleRequest
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
{
if(request.getURI()=="/command") {
EachInputValue(request, [&](const char *id, const char *command){
wdmEventData tmp = {std::atoi(id), command};
wdmSystem::getInstance()->addEvent(tmp);
});
response.setContentType("text/plain");
response.setContentLength(2);
std::ostream &ostr = response.send();
ostr.write("ok", 3);
}
else if(request.getURI()=="/data") {
std::vector<wdmID> nodes;
nodes.push_back(_wdmGetRootNode()->getID());
EachNodeValue(request, [&](const char *id){
nodes.push_back(std::atoi(id));
});
wdmString json;
wdmJSONRequest request = {false, false, &json, nodes.empty() ? NULL : &nodes[0], (uint32_t)nodes.size()};
wdmSystem::getInstance()->requestJSON(request);
while(!request.done) { Poco::Thread::sleep(2); }
if(request.canceled) { json="[]"; }
response.setContentType("application/json");
response.setContentLength(json.size());
std::ostream &ostr = response.send();
ostr.write(&json[0], json.size());
}
}
示例3: handleRequestImpl
void GetServiceHandler::handleRequestImpl(Poco::Net::HTTPServerRequest & httpRequest, Poco::Net::HTTPServerResponse & httpResponse) {
SOAP::CommonSoapPreprocessing soapHandling(_grammarProvider);
soapHandling.parse(httpRequest.stream());
const auto soapAction(soapHandling.normalizedMessage->Header().Action().get());
std::unique_ptr<SOAP::Command> command(new SOAP::SoapFaultCommand(httpResponse));
if (soapAction == DPWS::GetMetadataTraits::RequestAction()) {
const std::string serverAddress(httpRequest.serverAddress().toString());
command = std::unique_ptr<SOAP::Command>(new SOAP::GetMetadataActionCommand(std::move(soapHandling.normalizedMessage), _service.getMetadata(serverAddress)));
} else if (soapAction == GetMDIBTraits::RequestAction()) {
command = std::unique_ptr<SOAP::Command>(new SOAP::GenericSoapActionCommand<GetMDIBTraits>(std::move(soapHandling.normalizedMessage), _service));
} else if (soapAction == GetMDDescriptionTraits::RequestAction()) {
command = std::unique_ptr<SOAP::Command>(new SOAP::GenericSoapActionCommand<GetMDDescriptionTraits>(std::move(soapHandling.normalizedMessage), _service));
} else if (soapAction == GetMdStateTraits::RequestAction()) {
command = std::unique_ptr<SOAP::Command>(new SOAP::GenericSoapActionCommand<GetMdStateTraits>(std::move(soapHandling.normalizedMessage), _service));
} else {
log_error([&] { return "GetServiceHandler can't handle action: " + soapAction; });
}
std::unique_ptr<MESSAGEMODEL::Envelope> responseMessage(command->Run());
SOAP::SoapHTTPResponseWrapper response(httpResponse);
response.send(SOAP::NormalizedMessageSerializer::serialize(*responseMessage));
}
示例4: build_message
bool RESTHandler::build_message(Poco::Net::HTTPServerRequest &request, Poco::Net::HTMLForm &form, Poco::URI &url,
zmqpp::message &msg) {
Json::Value root;
bool ok = false;
/// Find 'args' param in query or as POST body
if (form.has("args")) {
ok = reader.parse(form.get("args"), root);
} else if (request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST) {
ok = reader.parse(request.stream(), root);
}
if (!ok || !root.isArray()) {
return false;
}
if (verbose) {
std::clog << "0\t" << url.getPath().substr(1) << std::endl;
}
/// Get service name as path without leading slash
msg << url.getPath().substr(1);
for (size_t i = 0; i < root.size(); ++i) {
auto val = root.get(i, "");
if (!verbose)
msg << (val.isString() ? root.get(i, "").asString() : val.toStyledString());
else {
std::string s = (val.isString() ? root.get(i, "").asString() : val.toStyledString());
msg << s;
std::clog << (i + 1) << '\t' << s << std::endl;
}
}
return true;
}
示例5: canHandleRequest
bool WebSocketRoute::canHandleRequest(const Poco::Net::HTTPServerRequest& request,
bool isSecurePort) const
{
if(!BaseRoute_<WebSocketRouteSettings>::canHandleRequest(request, isSecurePort))
{
return false;
}
// check to see if this is an websocket upgrade request
if(Poco::icompare(request.get("Upgrade", ""), "websocket") != 0)
{
return false;
}
// TODO: firefox hack
// require websocket upgrade headers
// this is all fixed in Poco 1.4.6 and 1.5.+
std::string connectionHeader = Poco::toLower(request.get("Connection", ""));
if(Poco::icompare(connectionHeader, "Upgrade") != 0 &&
!ofIsStringInString(connectionHeader, "upgrade"))
{
// this request is coming from firefox, which is known to send things that look like:
// Connection:keep-alive, Upgrade
// thus failing the standard Poco upgrade test.
// we can't do this here, but will do a similar hack in the handler
return false;
}
return true;
}
示例6: handleRequest
void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) {
jsonrpc::handleRequest(response, [&](){
HttpServerHelpers::ReturnType ret = HttpServerHelpers::preprocess(p, request, response);
if (ret == HttpServerHelpers::RequestFinished){
return;
}
std::string serviceName = request.getURI();
std::cout << "servicename before: " << serviceName << std::endl;
if (serviceName.find('/') == 0) {
serviceName = serviceName.substr(1);
}
std::string::size_type question = serviceName.find('?');
if (question != std::string::npos) {
serviceName = serviceName.substr(0, question);
}
std::cout << "servicename after: " << serviceName << std::endl;
for (auto i = p.getRequestHandlers().begin(); i != p.getRequestHandlers().end(); i++){
if ((*i)->canHandle(serviceName)){
std::cout << "SPECIAL HANDLING of " << serviceName << std::endl;
(*i)->handle(request, response);
return;
}
}
//std::cout << "service name: " << serviceName << std::endl;
std::istream& rs = request.stream();
std::stringstream outstr;
Poco::StreamCopier::copyStream(rs, outstr);
std::string rsp;
std::string req = outstr.str();
//std::cout << "requset: " << req << std::endl;
//this->handlerProvider.GetHandler()
LTRACE("Json") << "request " << req << LE;
if (auto sHandlerProvider = handlerProvider.lock()) {
sHandlerProvider->getHandler(serviceName)->HandleRequest(req, rsp);
} else {
throw Poco::Exception("Request refused - server destroyed");
}
LTRACE("Json") << "response " << rsp << LE;
//std::cout << "response: " << rsp << std::endl;
response.setContentType("application/json");
response.sendBuffer(rsp.data(), rsp.length());
});
}
示例7: handleRequest
void ShowCaptchaPage::handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
{
m_log->trace("ShowCaptchaPage::handleRequest from "+request.clientAddress().toString());
std::map<std::string,QueryVar> queryvars;
CreateQueryVarMap(request,queryvars);
if(request.getVersion()==Poco::Net::HTTPRequest::HTTP_1_1)
{
response.setChunkedTransferEncoding(true);
}
std::string content="";
if(queryvars.find("UUID")!=queryvars.end())
{
std::string uuid=(*queryvars.find("UUID")).second.GetData();
SQLite3DB::Statement st=m_db->Prepare("SELECT MimeType,PuzzleData FROM tblIntroductionPuzzleRequests WHERE UUID=?;");
st.Bind(0,uuid);
st.Step();
if(st.RowReturned())
{
std::string mime;
std::string b64data;
std::vector<unsigned char> data;
st.ResultText(0,mime);
st.ResultText(1,b64data);
Base64::Decode(b64data,data);
// mime type should be short and have a / in it - otherwise skip
if(mime.size()<50 && mime.find('/')!=std::string::npos)
{
std::string fname(uuid);
if(mime=="image/bmp")
{
fname+=".bmp";
}
else if(mime=="audio/x-wav")
{
fname+=".wav";
}
response.setContentType(mime);
response.setContentLength(data.size());
response.set("Content-Disposition","attachment; filename="+fname);
content+=std::string(data.begin(),data.end());
}
}
}
std::ostream &ostr = response.send();
ostr << content;
}
示例8: handleRequest
void RESTHandler::handleRequest(Poco::Net::HTTPServerRequest &request,
Poco::Net::HTTPServerResponse &response) {
if (verbose) {
std::clog << "HTTP request " << request.getURI() << std::endl;
std::clog << "Context id: " << client.context_id() << std::endl;
}
zmqpp::message msg, reply;
/// Connect to broker if not connected
client.connect(broker);
Poco::URI url(request.getURI());
Poco::Net::HTMLForm form(request);
/// Filter by black list
if (black_list.find(url.getPath()) != black_list.end()) {
return error_black_list(response);
}
if (!build_message(request, form, url, msg)) {
return error_parse(response);
}
if (!client.send_request(msg, reply, (form.has("timeout") ? std::stoi(form.get("timeout")) : timeout))) {
return error_timeout(response);
}
/// Render response
response.setStatus(Poco::Net::HTTPServerResponse::HTTPStatus::HTTP_OK);
if (form.get("type", "json") == "json") {
/// JSON in single line (FastWriter)
std::string jsonp_callback = form.get("jsonp", form.get("callback", ""));
Json::Value packet(Json::ValueType::arrayValue);
response.setContentType("application/json");
std::ostream &out = response.send();
if (!jsonp_callback.empty())
out << jsonp_callback << "(";
for (size_t part = 0; part < reply.parts(); ++part)
packet.append(reply.get(part));
auto txt = writer.write(packet);
if (txt[txt.size() - 1] == '\n') // Cheat for EOL in serialization
txt = txt.substr(0, txt.size() - 1);
out << txt << (!jsonp_callback.empty() ? ")" : "") << std::flush;
} else {
/// Plain text wihtout delimiters
response.setContentType("text/plain");
std::ostream &out = response.send();
for (size_t part = 0; part < reply.parts(); ++part)
out.write((char *) reply.raw_data(part), reply.size(part));
out.flush();
}
}
示例9: dispatch
void RootReqDispatcher::dispatch(const Poco::Net::HTTPServerRequest& procReq,
Poco::Net::HTTPServerResponse &out)
{
using Poco::URI;
using std::string;
using std::vector;
// Construyo una URI
URI uri(procReq.getURI());
// Obtengo los segmentos del path
vector<string> pathSegs;
uri.getPathSegments(pathSegs);
if (pathSegs.size() == 0)
pathSegs.push_back(""); // Por consistencia
// Uso el primer segmento para determinar a donde despachar
TDispatchMap::iterator itDisp = dispatchMap_.find(pathSegs[0]);
// Si no encontré a donde mandarlo, es error
if (itDisp == dispatchMap_.end())
{
pErrorReqProc_->process(URI("/error?code=404"), out);
return;
}
// Lo mando a donde corresponda
itDisp->second->process(procReq, out);
}
示例10: handleRequest
void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
if (request.getContentType() == "application/soap+xml")
{
assert(false);
//std::string req(std::istreambuf_iterator<char>(request.stream()), std::istreambuf_iterator<char>());
//tinyxml2::XMLDocument reqDoc;
//reqDoc.Parse(req.c_str());
//tinyxml2::XMLDocument respDoc;
//respDoc.LoadFile(m_wsdl.c_str());
//cout << "Sending wsdl via soap" << endl << flush;
//m_outbuf = "";
//m_soapProtocol.SendResponse(reqDoc, respDoc, respDoc.FirstChildElement(), "http://www.w3.org/2005/08/addressing/anonymous");
//response.sendBuffer(m_outbuf.c_str(), m_outbuf.size());
//m_outbuf = "";
}
else
{
cout << "Sending wsdl via http" << endl << flush;
response.sendFile(m_wsdl.c_str(), "text/xml");
}
}
示例11:
/* virtual*/ void handleRequest(Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp)
{
resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK); //Sets the HTTP status code, Why?
resp.setContentType("text/html"); // set the content type of the message
ostream& out = resp.send(); //Returns an output stream for sending the response body. The returned stream is valid until the response object is destroyed.
out << "<h1>Hello world!</h1>" //Body of the repsonse
// << "<p>Count: " << ++count << "</p>"
<< "<p>Host: " << req.getHost() << "</p>" //Returns the value of the Host header field.
<< "<p>Method: " << req.getMethod() << "</p>"
<< "<p>URI: " << req.getURI() << "</p>";
out.flush();
cout << endl
//<< "Response sent for count=" << count
<< " Response sent for URI=" << req.getURI() << endl;
}
示例12: str
void Susi::WebSocketRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
Poco::Net::HTTPServerResponse& response) {
Poco::Net::WebSocket socket(request,response);
Poco::Net::NameValueCollection cookies;
request.getCookies(cookies);
std::string id = cookies["susisession"];
Susi::Logger::debug("register sender in ws");
apiServer->registerSender(id,[&socket](Susi::Util::Any & arg){
std::string msg = arg.toString();
Susi::Logger::debug("send frame to websocket");
socket.sendFrame(msg.data(), msg.length(), Poco::Net::WebSocket::FRAME_TEXT);
});
apiServer->onConnect(id);
char buffer[4096];
int flags;
size_t n;
while (true) {
n = socket.receiveFrame(buffer, sizeof(buffer), flags);
Susi::Logger::debug("got frame");
Susi::Logger::debug(std::to_string(n));
if(n==0 || (flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) == Poco::Net::WebSocket::FRAME_OP_CLOSE){
break;
}
std::string str(buffer, n);
Susi::Util::Any packet = Susi::Util::Any::fromString(str);
apiServer->onMessage(id,packet);
}
Susi::Logger::debug("closing websocket");
apiServer->onClose(id);
}
示例13: handleRequest
void TimeHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
Poco::Net::HTMLForm form(request, request.stream());
std::ostream& responseStream = response.send();
responseStream << "";
responseStream << "\n";
responseStream << "";
responseStream << "\n";
responseStream << "\n";
responseStream << "";
#line 6 "/ws/poco-1.3/PageCompiler/samples/HTTPTimeServer/src/TimeHandler.cpsp"
Poco::DateTime now;
std::string dt(Poco::DateTimeFormatter::format(now, "%W, %e %b %y %H:%M:%S %Z"));
responseStream << "\n";
responseStream << "<html>\n";
responseStream << "<head>\n";
responseStream << "<title>HTTPTimeServer powered by POCO C++ Libraries and PageCompiler</title>\n";
responseStream << "<meta http-equiv=\"refresh\" content=\"1\">\n";
responseStream << "</head>\n";
responseStream << "<body>\n";
responseStream << "<p style=\"text-align: center; font-size: 48px;\">";
#line 16 "/ws/poco-1.3/PageCompiler/samples/HTTPTimeServer/src/TimeHandler.cpsp"
responseStream << ( dt );
responseStream << "</p>\n";
responseStream << "</body>\n";
responseStream << "</html>\n";
responseStream << "";
}
示例14: destroySession
void BaseSessionStore::destroySession(Poco::Net::HTTPServerRequest& request,
Poco::Net::HTTPServerResponse& response)
{
// Get the cookies from the client.
Poco::Net::NameValueCollection cookies;
// Get the cookies
request.getCookies(cookies);
// Try to find a cookie with our session key name.
Poco::Net::NameValueCollection::ConstIterator cookieIter = cookies.begin();
while (cookieIter != cookies.end())
{
if (0 == cookieIter->first.compare(_sessionKeyName))
{
// Destroy the session data.
destroySession(cookieIter->second);
// Invalidate the cookies.
Poco::Net::HTTPCookie cookie(_sessionKeyName, cookieIter->second);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
++cookieIter;
}
}
示例15: canHandleRequest
bool FileSystemRoute::canHandleRequest(const Poco::Net::HTTPServerRequest& request,
bool isSecurePort) const
{
// require an HTTP_GET call
return request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET &&
BaseRoute::canHandleRequest(request, isSecurePort);
}