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

Get response from Poco http client to string

本文关键字:字符串 响应 获取 Poco http 客户端      更新时间:2023-10-16

我有一个小代码,它使用Poco库向本地web服务发送POST HTTP调用并获得响应。目前,我已经在带有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;
}

如何将响应消息存储在char数组或字符串中,而不打印或存储在文件中?

我不熟悉Poco,但你可以用std::ostringstream替换std::cout,然后从中取出字符串。

因此,与其这么做:

StreamCopier::copyStream(rs, cout);

使用此代码

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

或者,更直接地,您可以使用copyToString直接复制到std::string中,为自己保存至少一个分配+副本:

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