Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 776
Mr Alexander Avatar asked Mar 04 '15 11:03

Mr Alexander


1 Answers

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" ...
like image 88
xaizek Avatar answered Sep 22 '22 10:09

xaizek