6

尝试使用 libcurlpp(libcurl 的 C++ 包装器)发布表单并获得响应。一切正常,但我不知道如何在 http 事务完成后以编程方式访问 curlpp::Easy 对象的响应。基本上:

#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

当此代码运行时,因为Verbose设置为true我可以看到响应输出到 STDOUT。但是我如何才能访问完整的响应而不是将其转储到 STDOUT?curlpp::Easy 似乎没有任何方法可以访问响应。

谷歌中很多人问同样的问题,但没有回复。curlpp 邮件列表是一个死区,并且 curlpp 网站的 API 部分已经损坏了一年。

4

4 回答 4

14

这就是我最终做到的方式:

// 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();

一旦foo.perform()返回,完整的响应主体现在可以在WriteStream().

于 2011-02-18T07:26:07.667 回答
2

自从提出问题以来,也许 curlpp 已经更新。我正在使用在 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;
}
于 2017-11-10T12:14:44.817 回答
0

这是一个比其他一些例子更完整的例子。它借鉴了 Stephane 和 kometen 的答案,是我整理的代码,以确保我可以获得 HTTP 响应代码。

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;
}

针对我的示例服务器运行时的输出是:

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

(我的示例服务器返回 JSON。)

于 2020-10-19T16:47:58.780 回答
0

这段代码也有效,它来自这个答案

#include <curlpp/cURLpp.hpp>
#include <curlpp/Options.hpp>

// RAII cleanup

curlpp::Cleanup myCleanup;

// Send request and get a result.
// Here I use a shortcut to get it in a string stream ...

std::ostringstream os;
os << curlpp::options::Url(std::string("http://example.com"));

string asAskedInQuestion = os.str();
于 2021-06-30T17:09:09.750 回答