#include <boost/asio.hpp>
#include <iostream>
#include <boost/foreach.hpp>
#include <string>
#include <sstream>
#include <exception>
#include <iterator>
#include <functional>
#include <algorithm>
#include <fstream>
std::string Get_Http_1_1(std::string uri)
{
std::ostringstream request;
request<<"GET ";
request<<uri;
request<<" HTTP/1.1/n";
request<<"Connection:close /n/n";
return request.str();
}
int main(int argc, char* argv[])
{
try
{
boost::asio::ip::tcp::iostream netstream("google.cn","www");
netstream<<Get_Http_1_1("www.google.cn/index.html")<<std::flush;
std::ofstream out_file("index.html");
netstream>>out_file.rdbuf();
std::cout<<"receive data success"<<std::endl;
}
catch (const std::exception& e)
{
std::cout<<e.what()<<std::endl;
}
catch (...)
{
std::cout<<"unkown exception"<<std::endl;
}
}
#include <iostream>
#include <boost/foreach.hpp>
#include <string>
#include <sstream>
#include <exception>
#include <iterator>
#include <functional>
#include <algorithm>
#include <fstream>
std::string Get_Http_1_1(std::string uri)
{
std::ostringstream request;
request<<"GET ";
request<<uri;
request<<" HTTP/1.1/n";
request<<"Connection:close /n/n";
return request.str();
}
int main(int argc, char* argv[])
{
try
{
boost::asio::ip::tcp::iostream netstream("google.cn","www");
netstream<<Get_Http_1_1("www.google.cn/index.html")<<std::flush;
std::ofstream out_file("index.html");
netstream>>out_file.rdbuf();
std::cout<<"receive data success"<<std::endl;
}
catch (const std::exception& e)
{
std::cout<<e.what()<<std::endl;
}
catch (...)
{
std::cout<<"unkown exception"<<std::endl;
}
}
本文展示了一个使用 Boost.Asio 库的 C++ 程序实例,该程序通过 HTTP GET 请求从 google.cn 下载网页内容并保存到本地文件 index.html 中。程序首先创建 TCP 连接,然后发送 HTTP/1.1 GET 请求,最后将服务器响应的数据写入文件。
443

被折叠的 条评论
为什么被折叠?



