C ++でのHTTPリクエストの受信と送信方法は何ですか?
C++の場合、curlcppやcpprestsdkなどのサードパーティーライブラリを使用してHTTPリクエストを送受信することができます。以下は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://www.example.com にHTTP GETリクエストを送信し、応答メッセージの本文を response.txtファイルに保存します。必要に応じてコードを変更して異なる種類のHTTPリクエストを送信し、応答を処理できます。