Mr *_*der 4 c++ http stream httpclient poco
我有一个小代码,它使用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;
}
Run Code Online (Sandbox Code Playgroud)
如何将响应消息存储在char数组或字符串中而不打印或存储在文件中?
我不熟悉波科,但你可以只更换std::cout
与std::ostringstream
再拉弦出来.
所以不要这样做:
StreamCopier::copyStream(rs, cout);
Run Code Online (Sandbox Code Playgroud)
使用此代码
#include <sstream>
// ...
std::ostringstream oss;
StreamCopier::copyStream(rs, oss);
std::string response = oss.str();
// use "response" ...
Run Code Online (Sandbox Code Playgroud)
或者,更直接地,您可以使用copyToString
直接复制到a std::string
,至少节省一个分配+副本:
std::string responseStr;
StreamCopier::copyToString(rs, responseStr);
// use "responseStr" ...
Run Code Online (Sandbox Code Playgroud)