I have a small code that sends a POST HTTP call to a local web service and gets a response, using the Poco library. Currently I have the response message printed in the terminal with 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?
I'm not familiar with Poco, but you could just replace std::cout
with std::ostringstream
and then pull the string out of it.
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:
std::string responseStr;
StreamCopier::copyToString(rs, responseStr);
// use "responseStr" ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With