简体   繁体   English

从Poco http客户端获取响应字符串

[英]Get response from Poco http client to string

I have a small code that sends a POST HTTP call to a local web service and gets a response, using the Poco library. 我有一个小代码,它使用Poco库向本地Web服务发送POST HTTP调用并获得响应。 Currently I have the response message printed in the terminal with cout. 目前我在cout终端上打印了回复消息。

#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/StreamCopier.h"
#include <iostream>

using namespace std;
using namespace Poco::Net;
using namespace Poco;

int main (int argc, char* argv[])
{
    HTTPClientSession s("localhost", 8000);
    HTTPRequest request(HTTPRequest::HTTP_POST, "/test");
    s.sendRequest(request);

    HTTPResponse response;
    std::istream& rs = s.receiveResponse(response);
    StreamCopier::copyStream(rs, cout);

    return 0;
}

How can I have the response message stored in a char array or string and not printed or stored in a file? 如何将响应消息存储在char数组或字符串中,而不是打印或存储在文件中?

I'm not familiar with Poco, but you could just replace std::cout with std::ostringstream and then pull the string out of it. 我不熟悉Poco,但你可以用std::ostringstream替换std::cout ,然后将字符串拉出来。

So instead of doing: 所以不要这样做:

StreamCopier::copyStream(rs, cout);

use this code 使用此代码

#include <sstream>
// ...
std::ostringstream oss;
StreamCopier::copyStream(rs, oss);
std::string response = oss.str();
// use "response" ...

Or, more directly, you can use copyToString to copy directly into a std::string , saving yourself at least one allocation+copy: 或者,更直接地,您可以使用copyToString直接复制到std::string ,从而节省至少一个分配+副本:

std::string responseStr;
StreamCopier::copyToString(rs, responseStr);
// use "responseStr" ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM