C++ boost::asio::ip::tcp::iostream大法:像流一样进行Internet数据传输和接收

没装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所要的数据才会被传过来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值