#include <boost/asio.hpp>

#define USING_SSL   //是否加密

#ifdef USING_SSL
#include <boost/asio/ssl.hpp>
#endif using boost::asio::ip::tcp;
using std::string; int post(const string& host, const string& port, const string& page, const string& data, string& reponse_data)
{
try
{
boost::asio::io_service io_service;
//如果io_service存在复用的情况
// if(io_service.stopped())
// io_service.reset(); // 从dns取得域名下的所有ip
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, port);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // 尝试连接到其中的某个ip直到成功
#ifdef USING_SSL
boost::asio::ssl::context context(boost::asio::ssl::context::sslv23);
context.set_default_verify_paths();
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(io_service, context);
socket.set_verify_mode(boost::asio::ssl::context::verify_none);
boost::asio::connect(socket.lowest_layer(), endpoint_iterator);
socket.handshake(boost::asio::ssl::stream_base::client);
#else
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
#endif // Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
boost::asio::streambuf request;
std::ostream request_stream(&request); request_stream << "POST " << page << " HTTP/1.1\r\n";
request_stream << "Host: " << host << "\r\n";
request_stream << "Content-Length: " << data.length() << "\r\n";
// Content-Type: 视实际情况修改,or“application/octet-stream”
request_stream << "Content-Type: application/json; charset=UTF-8\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";
request_stream << data; // Send the request.
boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically
// grow to accommodate the entire line. The growth may be limited by passing
// a maximum size to the streambuf constructor.
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK.
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
{
reponse_data = "Invalid response";
return -2;
}
// 如果服务器返回非200都认为有错,不支持301/302等跳转
if (status_code != 200)
{
std::stringstream oss;
oss << "Response returned with status code" << " : " << status_code;
reponse_data = oss.str();
return -3;
} // 传说中的包头可以读下来了
std::string header;
std::vector<string> headers;
// string content_length_header("Content-Length: ");
// size_t content_length = 0;
while (std::getline(response_stream, header) && header != "\r")
{
/* if(string::npos != header.find(content_length_header))
{
string tmp(header.substr(content_length_header.size()));
stringstream ss;
ss << tmp;
ss >> content_length;
}*/
headers.push_back(header);
//std::cout << header << std::endl;
} // 读取所有剩下的数据作为包体
boost::system::error_code error;
while (boost::asio::read(socket, response,
boost::asio::transfer_at_least(1), error))
{
} // 返回值为eof,认为是正确的
if (error != boost::asio::error::eof && error.value() != 0x140000db)
{
std::stringstream oss;
oss << error.value() << " : " << error.message();
reponse_data = oss.str();
return -4;
} //响应有数据
if (response.size())
{
std::istream response_stream(&response);
std::istreambuf_iterator<char> eos;
reponse_data = string(std::istreambuf_iterator<char>(response_stream), eos);
}
}
catch(std::exception& e)
{
reponse_data = e.what();
return -1;
}
return 0;
}

 

参考资料:

跨平台c++/boost/asio 简单的HTTP POST请求 客户端模型
http://www.cnblogs.com/linbc/p/5034286.html

C++ Post/Get请求(Boost.Asio库)
https://blog.csdn.net/csnd_ayo/article/details/64437935

boost::asio ssl

https://blog.csdn.net/aalbertini/article/details/38300757

基于boost asio实现的支持ssl的通用socket框架

https://www.xuebuyuan.com/2178001.html

 

使用boost.asio实现网络通讯的更多相关文章

  1. Boost.Asio c++ 网络编程翻译(14)

    保持活动 假如,你须要做以下的操作: io_service service; ip::tcp::socket sock(service); char buff[512]; ... read(sock, ...

  2. Boost.Asio c++ 网络编程翻译(26)

    Boost.Asio-其他特性 这章我们讲了解一些Boost.Asio不那么为人所知的特性.标准的stream和streambuf对象有时候会更难用一些,但正如你所见.它们也有它们的益处.最后,你会看 ...

  3. asio的网络通讯代码练手

    asio的网络基本模板(单例模式 消息队列 ) // MyAsio.cpp: 定义控制台应用程序的入口点. // #include "stdafx.h" #include < ...

  4. Boost.Asio c++ 网络编程翻译(11)

    *_at方法 这些方法在一个流上面做随机存取操作.你来指定read和write操作从什么地方開始(offset): async_read_at(stream, offset, buffer [, co ...

  5. Boost.Asio c++ 网络编程翻译(20)

    异步服务端 这个图表是相当复杂的:从Boost.Asio出来你能够看到4个箭头指向on_accept.on_read,on_write和on_check_ping. 着也就意味着你永远不知道哪个异步调 ...

  6. Boost.Asio c++ 网络编程翻译(21)

    同步VS异步 Boost.Asio的作者做了一个非常惊艳的工作:它能够让你在同步和异步中自由选择,从而更好的适应你的应用. 在之前的章节中,我们学习了每种类型应用的框架,比方同步client,同步服务 ...

  7. Boost.Asio c++ 网络编程翻译(16)

    TCP异步服务端 核心功能和同步服务端的功能类似,例如以下: class talk_to_client : public boost::enable_shared_from_this<talk_ ...

  8. Boost.Asio c++ 网络编程翻译(10)

    read/write方法 这些方法对一个流进行读写操作(能够是套接字,或者其它表现的像流的类): async_read(stream, buffer [, completion],handler):这 ...

  9. Boost.Asio c++ 网络编程翻译(18)

    同步服务端 同步服务端也相当简单.它须要两个线程,一个负责接收新的client.另外一个负责处理已经存在的client. 它不能使用单线程:等带一个新的client是一个堵塞操作,所以我们须要另外一个 ...

随机推荐

  1. 【Leetcode】【Medium】Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  2. Python中GBK, UTF-8和Unicode的编码问题

    编码问题,一直是使用python2时的一块心病.几乎所有的控制台输入输出.IO操作和HTTP操作都会涉及如下的编码问题: UnicodeDecodeError:‘ascii’codec can’t d ...

  3. January 25 2017 Week 4 Wednesday

    In every triumph, there's a lot of try. 每个胜利背后都有许多尝试. There's a lot of try behind every success, and ...

  4. 用eclipse pydev 创建一个新py文件时 文件的coding设置问题

    问题: 当安装好eclipse和pydev后,创建一个project, 创建一个新的py文件,文件头都会自带中文时间.这样在编译的时候会报错. 解决办法之一: 通过设置,可以使新建的文件的文件头自动带 ...

  5. 文件是数据(字节)流的抽象-为什么C++中会把文件操作抽象为fstream?

    这不过是返祖罢了.正确的问题是为什么会把数据流抽象成文件. 设备-字节流-文件. 一切皆为文件,所有不同种类的类型都被抽象成文件(比如:块设备,socket套接字,pipe队列). 文件抽象为数据流一 ...

  6. 五·管理mysql

    在上一篇文章中 四·安装mysql-5.7.16-linux-glibc2.5-x86_64.tar.gz(基于Centos7源码安装) 已经安装好了mysql,也正常启动了.本篇文章主要内容是管理m ...

  7. Educational Codeforces Round 55 (Rated for Div. 2) B. Vova and Trophies 【贪心 】

    传送门:http://codeforces.com/contest/1082/problem/B B. Vova and Trophies time limit per test 2 seconds ...

  8. 有gridview汇出word和excel

    private void Export(GridView _gv, string filetype, string FileName)    {        if (filetype == &quo ...

  9. 关于Queue的相关问题

    在多线程中使用Queue,发现总是有莫名的问题, 经折腾好久之后发现是因为没有加锁! 以下测试代码中, 如果不加锁, 添加 100W对象, 可能只会成功50W, 然后并不会产生异常! );//(如果初 ...

  10. Tomcat整体介绍

    来源 本文整理自 <Tomcat内核设计剖析>.<Tomcat结构解析> Tomcat 整体架构 ​ 如上图所示:包含了Tomcat内部的主要组件,每个组件之间的层次包含关系很 ...