有什么方法可以简单地用c++发出HTTP请求吗?具体来说,我想下载一个页面(一个API)的内容,并检查内容,看看它是否包含1或0。是否也可以将内容下载到字符串中?


当前回答

你可以使用embeddedRest库。它是一个轻量级的头文件库。所以很容易将它包含到你的项目中,它不需要编译,因为里面没有。cpp文件。

从自述文件中请求示例。Md from repo:

#include "UrlRequest.hpp"

//...

UrlRequest request;
request.host("api.vk.com");
const auto countryId = 1;
const auto count = 1000;
request.uri("/method/database.getCities",{
    { "lang", "ru" },
    { "country_id", countryId },
    { "count", count },
    { "need_all", "1" },
});
request.addHeader("Content-Type: application/json");
auto response = std::move(request.perform());
if (response.statusCode() == 200) {
  cout << "status code = " << response.statusCode() << ", body = *" << response.body() << "*" << endl;
}else{
  cout << "status code = " << response.statusCode() << ", description = " << response.statusDescription() << endl;
}

其他回答

我也有同样的问题。Libcurl真的很完整。如果您需要c++库,可能会对c++包装器curlpp感兴趣。neon是另一个有趣的C库,它也支持WebDAV。

如果你使用c++, curlpp看起来很自然。源代码发行版中提供了许多示例。 要获取URL的内容,你可以这样做(从示例中提取):

// Edit : rewritten for cURLpp 0.7.3
// Note : namespace changed, was cURLpp in 0.7.2 ...

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

参见curlpp源代码分发中的示例目录,有很多更复杂的情况,以及使用curlpp的简单完整的最小情况。

我的2美分…

cesanta的猫鼬库似乎也支持这一点:https://github.com/cesanta/mongoose/blob/6.17/examples/http_client/http_client.c

2020年4月的最新答案:

最近,我使用cppp -httplib(作为客户机和服务器)取得了很大的成功。它是成熟的,它的近似,单线程RPS约为6k。

更先进的是,有一个非常有前途的框架,cpv-framework,它可以在两个核上获得大约180k RPS(并且可以很好地扩展核的数量,因为它基于sestar框架,它为地球上最快的db scylladb提供动力)。

但是cpv-framework还比较不成熟;所以,对于大多数用途,我强烈推荐cppp -httplib。

这个建议取代了我之前的答案(8年前)。

你可能想要检查c++ REST SDK(代号“Casablanca”)。http://msdn.microsoft.com/en-us/library/jj950081.aspx

使用c++ REST SDK,您可以更轻松地从c++应用程序连接到HTTP服务器。

使用的例子:

#include <iostream>
#include <cpprest/http_client.h>

using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features

int main(int argc, char** argv) {
    http_client client("http://httpbin.org/");

    http_response response;
    // ordinary `get` request
    response = client.request(methods::GET, "/get").get();
    std::cout << response.extract_string().get() << "\n";

    // working with json
    response = client.request(methods::GET, "/get").get();
    std::cout << "url: " << response.extract_json().get()[U("url")] << "\n";
}

c++ REST SDK是微软的一个项目,用于使用现代异步c++ API设计的本地代码进行基于云的客户端-服务器通信。

如果你想要c++的解决方案,你可以使用Qt,它有一个QHttp类。

你可以查看文档:

http->setHost("qt.nokia.com");
http->get(QUrl::toPercentEncoding("/index.html"));

Qt还有很多可以在普通c++应用程序中使用的功能。