Get a response from the Poco http client on the line

I have a little code that sends a POST HTTP message to a local web service and receives a response using the Poco library. I currently have a response message printed in the cout terminal.

#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 get a response message stored in an array or char string and not printed or stored in a file?

+4
source share
1 answer

I am not familiar with Poco, but you can just replace std::coutwith std::ostringstreamand then pull a string from it.

So instead:

StreamCopier::copyStream(rs, cout);

use this code

#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" ...
+8

All Articles