温馨提示×

c++中http请求怎么接收和发送

c++
小亿
354
2024-02-18 09:58:15
栏目: 编程语言

在C++中,可以使用第三方库来发送和接收HTTP请求,比如curlcpp、cpprestsdk等。下面是一个使用cpprestsdk库发送HTTP GET请求的示例代码:

#include <cpprest/http_client.h> #include <cpprest/filestream.h> using namespace web; using namespace web::http; using namespace web::http::client; int main() { // 创建一个http_client对象 http_client client(U("http://www.example.com")); // 发送一个GET请求 client.request(methods::GET).then([](http_response response) { if (response.status_code() == status_codes::OK) { // 将响应消息主体保存到文件中 concurrency::streams::ofstream::open_ostream(U("response.txt")).then([=](concurrency::streams::ostream output) { return response.body().read_to_end(output.streambuf()); }).then([=](size_t) { // 读取完成 std::wcout << L"File saved" << std::endl; }).wait(); } }).wait(); return 0; } 

以上代码使用cpprestsdk库发送一个HTTP GET请求到http://www.example.com,并将响应消息主体保存到response.txt文件中。你可以根据需要修改代码来发送不同类型的HTTP请求和处理响应。

0