【问题标题】:How to receive POST request content in Poco?如何在 Poco 中接收 POST 请求内容?
【发布时间】:2016-03-01 16:00:05
【问题描述】:

我在 Poco 中编写了一个 HTTP 客户端,它将 POST 请求发送到 HTTPServer 以下是sn-p

Poco::Net::HTTPClientSession s("127.0.0.1", 9090);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/echo");

std::string body("rs=this is a random request body");
request.setContentLength(body.length());
s.sendRequest(request) << body;

服务器收到请求,但以下是我能找到的唯一获得蒸汽的方法(即 rs=this is a ....)

void SRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& hreq, Poco::Net::HTTPServerResponse& resp){
std::istream &i = hreq.stream();
        Poco::StreamCopier::copyStream(i, ss, hreq.getContentLength());
}

所以剩下的获取客户端发送的内容的方法是使用字符串。 有没有更简单/直接的方式来获取内容?

【问题讨论】:

    标签: poco-libraries


    【解决方案1】:

    你可以试试 Poco/Net/HTMLForm:

    Poco::Net::HTMLForm form(hreq, hreq.stream());
    

    然后您可以使用 form.get("rs") 或 form["rs"] 来获取带有值的 std::string。

    https://pocoproject.org/docs/Poco.Net.HTMLForm.html

    【讨论】:

      【解决方案2】:

      您当前正在执行的操作不涉及任何字符串 - 您正在从 istream 复制到 ostream。如果您想避免这种情况,可以将 istream 的内容读入 char 数组,如下所示:

      std::istream &i = hreq.stream();
      int len = hreq.getContentLength();
      char* buffer = new char[len];
      i.read(buffer, len);
      

      当然,您应该注意避免泄漏。

      【讨论】:

      • 感谢您的回复。但我的问题不是关于如何从字符串或字符串缓冲区中读取,而是关于 poco 库的使用,还有没有其他方法可以在不读取完整流的情况下获取帖子内容,或者 Poco 是否提供任何 API 来读取 POST 内容。
      • 你的问题不是很清楚。由于内容显然在流中,那么将其取出的唯一方法就是从流中提取它。存在其他选项,但不涉及 Poco HTTP 框架 - 您可以使用 Poco ServerSocket、解析标头等创建自己的 TCP 服务器...
      【解决方案3】:

      Alex 在现代 C++ 中的回答(用 C++17 测试)std::string

      auto & stream = hreq.stream();
      const size_t len = hreq.getContentLength();
      std::string buffer(len, 0);
      stream.read(buffer.data(), len);
      

      【讨论】:

        猜你喜欢
        • 2013-08-17
        • 2018-10-04
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 2015-09-15
        • 2011-04-14
        • 2012-02-03
        • 1970-01-01
        相关资源
        最近更新 更多