没装boost的先去安装boost:-)
Python的requests库真是好呀,不过C++有比它更好的:boost::asio。
boost::asio::ip::tcp::iostream:<<表示发送,>>表示接收。构造函数:boost::asio::ip::tcp::iostream s(服务器名,协议名)。
示例代码(作用:下载CSDN logo):
#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <fstream>
std::string get_http_data(const std::string& server, const std::string& file)
{
try
{
boost::asio::ip::tcp::iostream s(server, "http");
s.expires_from_now(boost::posix_time::seconds(60));
if (!s){ throw "Unable to connect: " + s.error().message(); }
//问服务器要文件
s << "GET " << file << " HTTP/1.0\r\n";
s << "Host: " << server << "\r\n";
s << "Accept: */*\r\n";
s << "Connection: close\r\n\r\n";
//看看回复是不是完好的
std::string http_version;
s >> http_version;
unsigned int status_code;
s >> status_code;
std::string status_message;
std::getline(s, status_message);
if (!s && http_version.substr(0, 5) != "HTTP/"){ throw "Invalid response\n"; }
if (status_code != 200){ throw "Response returned with status code " + status_code; }
// 去除响应头,它以'\r'结尾。
std::string header;
while (std::getline(s, header) && header != "\r"){}
//返回一个字符串(包含所有数据)
std::stringstream ss;
ss << s.rdbuf();
return ss.str();
}
catch(std::exception& e)
{
return e.what();
}
}
int main()
{
//https://csdnimg.cn/cdn/content-toolbar/csdn-logo.png?v=20200416.1
std::string result = get_http_data("csdnimg.cn", "/cdn/content-toolbar/csdn-logo.png");
std::ofstream of("csdn-logo.png", std::ios::binary);
of << result;
}
需要注意的是,boost::asio::ip::tcp::iostream 是要多少数据就传输多少,也就是说只有执行到s>>xxx时xxx所要的数据才会被传过来。