4

Trying to use libcurlpp (a C++ wrapper to libcurl) to post a form and get the response. It all works, but I have no idea how to programmatically get access to the response from the curlpp::Easy object after the http transaction has finished. Bascially:

#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
...
curlpp::Easy foo;
foo.setOpt( new curlpp::options::Url( "http://example.com/" ) );
foo.setOpt( new curlpp::options::Verbose( true ) );
...many other options set...
foo.perform();  // this executes the HTTP transaction

When this code runs, because Verbose is set to true I can see the response get output to STDOUT. But how do I get access to the full response instead of having it dump to STDOUT? The curlpp::Easy doesn't seem to have any methods to gain access to the response.

Lots of hits in Google with people asking the same question, but no replies. The curlpp mailing list is a dead zone, and API section of the curlpp web site has been broken for a year.

Stéphane
  • 17,613
  • 22
  • 82
  • 117

3 Answers3

13

This is how I finally did it:

// HTTP response body (not headers) will be sent directly to this stringstream
std::stringstream response;

curlpp::Easy foo;
foo.setOpt( new curlpp::options::Url( "http://www.example.com/" ) );
foo.setOpt( new curlpp::options::UserPwd( "blah:passwd" ) );
foo.setOpt( new curlpp::options::WriteStream( &response ) );

// send our request to the web server
foo.perform();

Once foo.perform() returns, the full response body is now available in the stream provided in WriteStream().

Stéphane
  • 17,613
  • 22
  • 82
  • 117
2

Maybe curlpp have been updated since the question was asked. I'm using this which I found in example04.cpp.

#include <curlpp/Infos.hpp>

long http_code = 0;
request.perform();
http_code = curlpp::infos::ResponseCode::get(request);
if (http_code == 200) {
    std::cout << "Request succeeded, response: " << http_code << std::endl;
} else {
    std::cout << "Request failed, response: " << http_code << std::endl;
}
kometen
  • 4,305
  • 3
  • 36
  • 39
0

This is a slightly more complete example than some of the others. It borrows from the answers from Stephane and kometen and is code I put together to ensure I could get the HTTP response codes.

void
runBadQuery() {
    curlpp::Easy request;
    std::ostringstream stream;

    request.setOpt<curlpp::options::Url>("http://localhost:3010/bad");
    request.setOpt( new curlpp::options::WriteStream( &stream ) );
    request.perform();

    long http_code = curlpp::infos::ResponseCode::get(request);
    cout << "/bad got code: " << http_code << " And content: " << stream.str() << endl;
}

Output when run against my sample server is:

/bad got code: 400 And content: {
  "error": "Illegal request"
}

(My sample server returns JSON.)

Joseph Larson
  • 4,851
  • 1
  • 15
  • 25