当前位置: 首页>>代码示例>>C++>>正文


C++ HTTPServerRequest::getURI方法代码示例

本文整理汇总了C++中poco::net::HTTPServerRequest::getURI方法的典型用法代码示例。如果您正苦于以下问题:C++ HTTPServerRequest::getURI方法的具体用法?C++ HTTPServerRequest::getURI怎么用?C++ HTTPServerRequest::getURI使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在poco::net::HTTPServerRequest的用法示例。


在下文中一共展示了HTTPServerRequest::getURI方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: 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());
        }
    }
开发者ID:ezhangle,项目名称:WebDebugMenu,代码行数:31,代码来源:WebDebugMenu.cpp

示例2: 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();
    }


}
开发者ID:ruslanec,项目名称:waha,代码行数:48,代码来源:http.cpp

示例3:

   /* 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;
    }
开发者ID:ppezzini,项目名称:http_Server,代码行数:16,代码来源:MyRequestHandler.cpp

示例4: 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);
}
开发者ID:mchouza,项目名称:ngpd,代码行数:29,代码来源:root_req_dispatcher.cpp

示例5: 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;
						}
					}

					throw Poco::FileNotFoundException("File not found");

				});
			}
开发者ID:hadzim,项目名称:bb,代码行数:34,代码来源:HttpServer.cpp

示例6: handleRequest

	virtual void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response)
	{
		if (request.getURI() == "/name")
		{
			response.setContentType("application/json");
			response.send() << " { \"hanwenfang\"} ";
		}
	}
开发者ID:HanWenfang,项目名称:Restful-Service-Backend,代码行数:8,代码来源:HelloWorld.cpp

示例7: 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());
				});
			}
开发者ID:hadzim,项目名称:bb,代码行数:58,代码来源:httpinterfaceserver.cpp

示例8: DefaultRequestHandler

void DefaultRequestHandler(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
  response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
  response.setContentType(Poco::Net::MediaType("text/plain"));
  response.setKeepAlive(true);
  auto& os = response.send();

  os << "It Works! " << request.getURI() << std::flush;
}
开发者ID:elkvis,项目名称:PocoHttpRouter,代码行数:9,代码来源:HttpRouterTest.cpp

示例9: handleRequest

void FileRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
    setContentType(request, response);
    std::ostream& ostr = response.send();
    try {
        Poco::Path basedir = Poco::Util::Application::instance().config().getString("application.dir");
        basedir.append("web");
        basedir.append(request.getURI());
        Poco::FileInputStream fis(basedir.toString());
        Poco::StreamCopier::copyStream(fis, ostr);
        response.setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
    }
    catch (Poco::Exception& ex) {
        response.setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND);
        ostr << ex.displayText();
        _logger.error("Request failed: %s: %s", request.getURI(), ex.displayText());
    }

}
开发者ID:dtylman,项目名称:ion,代码行数:19,代码来源:FileRequestHandler.cpp

示例10: setContentType

void FileRequestHandler::setContentType(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
    Poco::Path path(request.getURI());
    std::string extension = Poco::toLower(path.getExtension());
    if (extension == "css") {
        response.setContentType("text/css");
    }
    else if (extension == "js") {
        response.setContentType("application/javascript");
    }
    else {
        response.setContentType("text/html");
    }
}
开发者ID:dtylman,项目名称:ion,代码行数:14,代码来源:FileRequestHandler.cpp

示例11: filterHandleRequest

    virtual bool filterHandleRequest(
                     TestRequest type,
                     Poco::Net::HTTPServerRequest& request,
                     Poco::Net::HTTPServerResponse& response) override
    {
        if (type == UnitWSD::TestRequest::TEST_REQ_PRISONER &&
            request.getURI().find(UNIT_URI) == 0)
        {
            auto ws = std::make_shared<Poco::Net::WebSocket>(request, response);
            _fontsBroker = readFontList(ws);
            check();
            return true;
        }

        return false;
    }
开发者ID:BJFletcher94,项目名称:online,代码行数:16,代码来源:UnitFonts.cpp

示例12: handleRequest

void FileSystemRouteHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
        Poco::Net::HTTPServerResponse& response)
{
    Poco::Path dataFolder(ofToDataPath("",true));
    Poco::Path documentRoot(ofToDataPath(_parent.getSettings().getDocumentRoot(),true));

    std::string dataFolderString = dataFolder.toString();
    std::string documentRootString = documentRoot.toString();

    // doc root validity check
    if(_parent.getSettings().getRequireDocumentRootInDataFolder() &&
            (documentRootString.length() < dataFolderString.length() ||
             documentRootString.substr(0,dataFolderString.length()) != dataFolderString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Document Root is not a sub directory of the data folder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
        return;
    }

    // check path

    Poco::URI uri(request.getURI());
    std::string path = uri.getPath(); // just get the path

    // make paths absolute
    if(path.empty())
    {
        path = "/";
    }

    Poco::Path requestPath = documentRoot.append(path).makeAbsolute();

    // add the default index if no filename is requested
    if(requestPath.getFileName().empty())
    {
        requestPath.append(_parent.getSettings().getDefaultIndex()).makeAbsolute();
    }

    std::string requestPathString = requestPath.toString();

    // double check path safety (not needed?)
    if((requestPathString.length() < documentRootString.length() ||
            requestPathString.substr(0,documentRootString.length()) != documentRootString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Requested document not inside DocumentFolder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
        return;
    }

    ofFile file(requestPathString); // use it to parse file name parts

    try
    {
//        ofx::Media::MediaTypeMap mediaMap;
//        Poco::Net::MediaType mediaType = mediaMap.getMediaTypeForSuffix(file.getExtension());

        std::string mediaTypeString = "application/octet-stream";
        std::string ext = file.getExtension();


        if(ext == "json")
        {
            mediaTypeString = "application/json";
        }
        else if(ext == "html")
        {
            mediaTypeString = "text/html";
        }
        else if(ext == "jpg" || ext == "jpeg")
        {
            mediaTypeString = "image/jpeg";
        }
        else if(ext == "png")
        {
            mediaTypeString = "image/png";
        }
        else if(ext == "js")
        {
            mediaTypeString = "application/javascript";
        }
        else if(ext == "css")
        {
            mediaTypeString = "text/css";
        }
        else if(ext == "xml")
        {
            mediaTypeString = "application/xml";
        }
        else if(ext == "ico")
        {
            mediaTypeString = "image/x-icon";
        }

        response.sendFile(file.getAbsolutePath(), mediaTypeString); // will throw exceptions
        return;
    }
    catch (const Poco::FileNotFoundException& ex)
    {
//.........这里部分代码省略.........
开发者ID:jvcleave,项目名称:RPiCameraRemoteServer,代码行数:101,代码来源:FileSystemRouteHandler.cpp

示例13: handleRequest

void AppRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
	// Check for the favicon.ico request, we don't have one for now,
	// so set status code to HTTP_NOT_FOUND
	if ( request.getURI().compare("/favicon.ico") == 0 )
	{
		response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
		response.send();
		return;
	}

	std::string lastModifiedHeader = request.get("If-Modified-Since", "");

	Poco::URI uri(request.getURI());

	Poco::Util::Application& app = Poco::Util::Application::instance();
	std::string staticPathname = app.config().getString("mq.web.app", "");
	if ( staticPathname.empty() )
	{
		Poco::Logger& logger = Poco::Logger::get("mq.web");
		logger.error("mq.web.app property not defined. Check your configuration.");
		response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
		response.send();
		return;
	}

	Poco::Path staticPath(staticPathname);
	staticPath.makeDirectory();

	std::vector<std::string> uriPathSegments;
	uri.getPathSegments(uriPathSegments);
	std::vector<std::string>::iterator it = uriPathSegments.begin();
	it++;
	for(; it != uriPathSegments.end(); ++it)
	{
		staticPath.append(*it);
	}
	if (staticPath.isDirectory())
	{
		staticPath.append("index.html");
	}

	Poco::File staticFile(staticPath);

	Poco::Logger& logger = Poco::Logger::get("mq.web.access");
	if ( staticFile.exists() )
	{
		if ( !lastModifiedHeader.empty() )
		{
			Poco::DateTime lastModifiedDate;
			int timeZoneDifferential = 0;
			if ( Poco::DateTimeParser::tryParse(Poco::DateTimeFormat::HTTP_FORMAT, lastModifiedHeader, lastModifiedDate, timeZoneDifferential) )
			{
				if ( staticFile.getLastModified() <= lastModifiedDate.timestamp() )
				{
					logger.information(Poco::Logger::format("$0 : HTTP_NOT_MODIFIED", staticPath.toString()));
					response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED);
					response.send();
					return;
				}
			}
		}

		logger.information(Poco::Logger::format("$0 : HTTP_OK", staticPath.toString()));

		std::string mimeType;
		if ( staticPath.getExtension().compare("gif") == 0 )
		{
			mimeType = "image/gif";
		}
		else if ( staticPath.getExtension().compare("css") == 0 )
		{
			mimeType = "text/css";
		}
		else if ( staticPath.getExtension().compare("html") == 0 || staticPath.getExtension().compare("htm") == 0)
		{
			mimeType = "text/html";
		}
		else if ( staticPath.getExtension().compare("js") == 0 )
		{
			mimeType = "text/javascript";
		}
		else if ( staticPath.getExtension().compare("png") == 0 )
		{
			mimeType = "image/png";
		}
		else if ( staticPath.getExtension().compare("jpg") == 0 || staticPath.getExtension().compare("jpeg") == 0)
		{
			mimeType = "image/jpeg";
		}

		try
		{
			response.sendFile(staticPath.toString(), mimeType);
		}
		catch(Poco::FileNotFoundException&)
		{
			// We can't get here normally ... but you never know :)
			response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, Poco::Logger::format("Can't find file $0", staticPath.toString()));
		}
//.........这里部分代码省略.........
开发者ID:fbraem,项目名称:mqweb,代码行数:101,代码来源:AppRequestHandler.cpp

示例14: handleRequest

	void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
	{
		//Poco::Util::Application& app = Poco::Util::Application::instance();
		//app.logger().information("Request from " + request.clientAddress().toString());
        std::cout << "Request from " << request.clientAddress().toString() << std::endl;

        MyPartHandler partHandler;
        Poco::Net::HTMLForm form(request, request.stream(), partHandler);

        std::string spinToken, sceneString, nodeString, args;
        std::istringstream pathstream(request.getURI());
        pathstream.get(); // ignore leading slash
        getline(pathstream, spinToken, '/');
        getline(pathstream, sceneString, '/');
        getline(pathstream, nodeString, '?');

        if (sceneString.empty()) sceneString = "default";
        //if (nodeString.empty()) nodeString = "shp";
        if (form.empty()) args = "createNode shp ShapeNode";
        else args = form["args"];

        response.setChunkedTransferEncoding(true);
        response.setContentType("text/html");

        std::ostream& ostr = response.send();

        ostr <<
        "<html>\n"
        "<head>\n"
        "<title>SPIN Web Service</title>\n"
        "</head>\n"
        "<body>\n"
        "<h1>SPIN Web Service</h1>\n"
        "<h3>Enter a SPIN command in the form below:</h3>\n"
        "<table><tr><td nowrap=\"nowrap\">\n"
        "<form name=\"urlForm\" method=\"GET\" action=\"null\">\n"
        "/SPIN/"
        "<input type=\"text\" name=\"sceneID\" value=\"" << sceneString << "\" size=\"10\">\n"
        "/<input type=\"text\" name=\"nodeID\" value=\"" << nodeString << "\" size=\"10\">"
        "</form></td>\n"
        "<td nowrap=\"nowrap\">\n"
        "<form name=\"spinform\" method=\"GET\" action=\"null\">\n"
        "<input type=\"text\" name=\"args\" value=\"" << args << "\" size=\"20\">\n"
        "<input type=\"submit\" value=\"GO\" onclick=\"this.form.action='/SPIN/'+document.forms['urlForm']['sceneID'].value+'/'+document.forms['urlForm']['nodeID'].value\">\n"
        "</form>\n"
        "</tr></table>\n"
        "<p>(NOTE: you can send scene messages by leaving the node name blank)</p>\n"
        "\n";
        /*
        ostr <<
            "<html>\n"
            "<head>\n"
            "<title>SPIN Web Server Sample</title>\n"
            "</head>\n"
            "<body>\n"
            "<h1>SPIN Web Server Sample</h1>\n"
            "<h2>Tests:</h2>\n"
            "<form name=\"spinform\" method=\"GET\" action=\"null\">\n"
            "/SPIN/default/"
            "<input type=\"text\" name=\"nodeID\" value=\"shp\" size=\"15\">"
            "&nbsp;&nbsp;&nbsp;"
            "<input type=\"text\" name=\"method\" value=\"rotate\" size=\"15\">"
            " move<input type=\"text\" name=\"x\" value=\"0\" size=\"3\">"
            " <input type=\"text\" name=\"y\" value=\"0\" size=\"3\">"
            " <input type=\"text\" name=\"z\" value=\"10\" size=\"3\">\n"
            " <input type=\"submit\" value=\"GO\" onclick=\"this.form.action='/SPIN/default/'+this.form.nodeID.value\">\n"
            "</form>\n"
            "\n";
        ostr <<
            "<html>\n"
            "<head>\n"
            "<title>SPIN Web Server Sample</title>\n"
            "</head>\n"
            "<body>\n"
            "<h1>SPIN Web Server Sample</h1>\n"
            "<h2>GET Form</h2>\n"
            "<form method=\"GET\" action=\"/form\">\n"
            "<input type=\"text\" name=\"text\" size=\"31\">\n"
            "<input type=\"submit\" value=\"GET\">\n"
            "</form>\n"
            "<h2>POST Form</h2>\n"
            "<form method=\"POST\" action=\"/form\">\n"
            "<input type=\"text\" name=\"text\" size=\"31\">\n"
            "<input type=\"submit\" value=\"POST\">\n"
            "</form>\n"
            "<h2>File Upload</h2>\n"
            "<form method=\"POST\" action=\"/form\" enctype=\"multipart/form-data\">\n"
            "<input type=\"file\" name=\"file\" size=\"31\"> \n"
            "<input type=\"submit\" value=\"Upload\">\n"
            "</form>\n";
            */

        ostr << "<h2>Result</h2><p>\n";
        ostr << "Method: " << request.getMethod() << "<br>\n";
        ostr << "URI: " << request.getURI() << "<br>\n";
        Poco::Net::NameValueCollection::ConstIterator it = request.begin();
        Poco::Net::NameValueCollection::ConstIterator end = request.end();
        for (; it != end; ++it)
        {
            ostr << it->first << ": " << it->second << "<br>\n";
//.........这里部分代码省略.........
开发者ID:OuyeXie,项目名称:test_project,代码行数:101,代码来源:test_poco_server.cpp

示例15: handleRequest

void FileSystemRouteHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
                                           Poco::Net::HTTPServerResponse& response)
{
    Poco::Path dataFolder(ofToDataPath("", true));
    Poco::Path documentRoot(ofToDataPath(_parent.getSettings().getDocumentRoot(), true));

    std::string dataFolderString = dataFolder.toString();
    std::string documentRootString = documentRoot.toString();

    // doc root validity check
    if(_parent.getSettings().getRequireDocumentRootInDataFolder() &&
       (documentRootString.length() < dataFolderString.length() ||
        documentRootString.substr(0,dataFolderString.length()) != dataFolderString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Document Root is not a sub directory of the data folder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
        return;
    }

    // check path

    Poco::URI uri(request.getURI());
    std::string path = uri.getPath(); // just get the path

    // make paths absolute
    if(path.empty())
    {
        path = "/";
    }

    Poco::Path requestPath = documentRoot.append(path).makeAbsolute();

    // add the default index if no filename is requested
    if(requestPath.getFileName().empty())
    {
        requestPath.append(_parent.getSettings().getDefaultIndex()).makeAbsolute();
    }

    std::string requestPathString = requestPath.toString();

    // double check path safety (not needed?)
    if((requestPathString.length() < documentRootString.length() ||
        requestPathString.substr(0,documentRootString.length()) != documentRootString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Requested document not inside DocumentFolder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
        return;
    }

    ofFile file(requestPathString); // use it to parse file name parts
    std::string mediaTypeString = Media::MediaTypeMap::getDefault()->getMediaTypeForPath(file.path()).toString();

    try
    {
        // TODO: this is where we would begin to work honoring
        /// Accept-Encoding:gzip, deflate, sdch
        response.sendFile(file.getAbsolutePath(), mediaTypeString);
        return;
    }
    catch (const Poco::FileNotFoundException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
    }
    catch (const Poco::OpenFileException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
    catch (const exception& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Unknown server error: " << ex.what();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
}
开发者ID:jedahan,项目名称:ofxHTTP,代码行数:80,代码来源:FileSystemRouteHandler.cpp


注:本文中的poco::net::HTTPServerRequest::getURI方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。