C++ HTTP Requests: Send & Receive Guide
In C++, third-party libraries like curlcpp and cpprestsdk can be used to send and receive HTTP requests. Here is an example code using the cpprestsdk library to send an HTTP GET request.
#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;
}
The above code uses the cpprestsdk library to send an HTTP GET request to http://www.example.com and saves the response message body to a file named response.txt. You can modify the code as needed to send different types of HTTP requests and handle responses.