使用boost做post/get请求开发笔记
来源:互联网 发布:韩国恢复汉字 知乎 编辑:程序博客网 时间:2024/06/06 14:18
话不多说 上代码:代码也很简单,可以直接使用编译
#include <iostream>#include <istream>#include <ostream>#include <string>#include <boost/asio.hpp>#include <boost/bind.hpp>using boost::asio::ip::tcp;class client{public: client(boost::asio::io_service& io_service, const std::string& server, const std::string& path) : resolver_(io_service), socket_(io_service) { // 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. std::ostream request_stream(&request_); string postString = "tips=notips&messageType=targetResult&targetResult=passwdvideo" ; request_stream << "POST " << path << " HTTP/1.1\r\n"; request_stream << "Host: " << server << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Type: " << "application/x-www-form-urlencoded" << "\r\n"; request_stream << "Content-Length: " << postString.length() << "\r\n"; request_stream << "Connection: keep-alive\r\n\r\n"; request_stream << postString ; // Start an asynchronous resolve to translate the server and service names // into a list of endpoints. tcp::resolver::query query("192.168.1.46", "8187"); resolver_.async_resolve(query, boost::bind(&client::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator)); }private: void handle_resolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) { if (!err) { // Attempt a connection to each endpoint in the list until we // successfully establish a connection. boost::asio::async_connect(socket_, endpoint_iterator, boost::bind(&client::handle_connect, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_connect(const boost::system::error_code& err) { if (!err) { // The connection was successful. Send the request. boost::asio::async_write(socket_, request_, boost::bind(&client::handle_write_request, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_write_request(const boost::system::error_code& err) { if (!err) { // 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::async_read_until(socket_, response_, "\r\n", boost::bind(&client::handle_read_status_line, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_read_status_line(const boost::system::error_code& err) { if (!err) { // 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/") { std::cout << "Invalid response\n"; return; } if (status_code != 200) { std::cout << "Response returned with status code "; std::cout << status_code << "\n"; return; } // Read the response headers, which are terminated by a blank line. boost::asio::async_read_until(socket_, response_, "\r\n\r\n", boost::bind(&client::handle_read_headers, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_headers(const boost::system::error_code& err) { if (!err) { // Process the response headers. std::istream response_stream(&response_); std::string header; while (std::getline(response_stream, header) && header != "\r") std::cout << header << "\n"; std::cout << "\n"; // Write whatever content we already have to output. if (response_.size() > 0) std::cout << &response_; // Start reading remaining data until EOF. boost::asio::async_read(socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&client::handle_read_content, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_content(const boost::system::error_code& err) { if (!err) { printf("\n\ncontent is : \n\n"); // Write all of the data that has been read so far. std::cout << &response_; // Continue reading remaining data until EOF. boost::asio::async_read(socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&client::handle_read_content, this, boost::asio::placeholders::error)); } else if (err != boost::asio::error::eof) { std::cout << "Error: " << err << "\n"; } } tcp::resolver resolver_; tcp::socket socket_; boost::asio::streambuf request_; boost::asio::streambuf response_;};int main(int argc, char* argv[]){ try { boost::asio::io_service io_service; client c(io_service, "192.168.1.46:8187", "/handle_post_request");// client c(io_service, "192.168.1.46:8187", "/"); io_service.run(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0;}
遍历缓冲区序列的字节
buffers_iterator<>类模板可用于像遍历连续字节序列一样遍历缓冲区序列(如MutableBufferSequence 或 ConstBufferSequence).并提供了buffers_begin() 和 buffers_end()帮助函数, 会自动推断buffers_iterator<>的模板参数.
例如,从socket中读取一行数据,存入std::string中:
boost::asio::streambuf sb;...std::size_t n = boost::asio::read_until(sock, sb, '\n');boost::asio::streambuf::const_buffers_type bufs = sb.data();std::string line( boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + n);
把他整理成了 头文件 和源文件 分开的形式,方便 直接使用:
#include<boostHttpClient.h>boostHttpclient_c::boostHttpclient_c(boost::asio::io_service& io_service, const std::string& server, const std::string& path) : resolver_(io_service), socket_(io_service){// 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.std::ostream request_stream(&request_);string postString = "tips=notips&messageType=targetResult&targetResult=passwdvideo" ;request_stream << "POST " << path << " HTTP/1.1\r\n";request_stream << "Host: " << server << "\r\n";request_stream << "Accept: */*\r\n";request_stream << "Content-Type: " << "application/x-www-form-urlencoded" << "\r\n";request_stream << "Content-Length: " << postString.length() << "\r\n";request_stream << "Connection: keep-alive\r\n\r\n";request_stream << postString ;// Start an asynchronous resolve to translate the server and service names// into a list of endpoints.tcp::resolver::query query("192.168.1.46", "8187");resolver_.async_resolve(query,boost::bind(&boostHttpclient_c::handle_resolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator));}void boostHttpclient_c::handle_resolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator){if (!err){ // Attempt a connection to each endpoint in the list until we // successfully establish a connection. boost::asio::async_connect(socket_, endpoint_iterator, boost::bind(&boostHttpclient_c::handle_connect, this,boost::asio::placeholders::error));}else{ std::cout << "Error: " << err.message() << "\n";}}void boostHttpclient_c::handle_connect(const boost::system::error_code& err){if (!err){ // The connection was successful. Send the request. boost::asio::async_write(socket_, request_, boost::bind(&boostHttpclient_c::handle_write_request, this,boost::asio::placeholders::error));}else{ std::cout << "Error: " << err.message() << "\n";}}void boostHttpclient_c::handle_write_request(const boost::system::error_code& err){if (!err){ // 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. printf("http write OK start listen \n "); boost::asio::async_read_until(socket_, response_, "\r\n", boost::bind(&boostHttpclient_c::handle_read_status_line, this,boost::asio::placeholders::error));}else{ std::cout << "Error: " << err.message() << "\n";}}void boostHttpclient_c::handle_read_status_line(const boost::system::error_code& err){if (!err){ // 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/") {std::cout << "Invalid response\n";return; } if (status_code != 200) {std::cout << "Response returned with status code ";std::cout << status_code << "\n";return; } printf("response headers get OK \n "); // Read the response headers, which are terminated by a blank line. boost::asio::async_read_until(socket_, response_, "\r\n\r\n", boost::bind(&boostHttpclient_c::handle_read_headers, this,boost::asio::placeholders::error));}else{ std::cout << "Error: " << err << "\n";}}void boostHttpclient_c::handle_read_headers(const boost::system::error_code& err){if (!err){ // Process the response headers. std::istream response_stream(&response_); std::string header; while (std::getline(response_stream, header) && header != "\r")std::cout << header << "\n"; std::cout << "\n"; // Write whatever content we already have to output.// if (response_.size() > 0){//// std::cout << &response_;// boost::asio::streambuf::const_buffers_type bufs = response_.data();// std::string line(// boost::asio::buffers_begin(bufs),// boost::asio::buffers_begin(bufs) + response_.size());// std::cout << line;// } // Start reading remaining data until EOF. boost::asio::async_read(socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&boostHttpclient_c::handle_read_content, this,boost::asio::placeholders::error));}else{ std::cout << "Error: " << err << "\n";}}void boostHttpclient_c::handle_read_content(const boost::system::error_code& err){if (!err){ // Write all of the data that has been read so far.// std::cout << &response_; boost::asio::streambuf::const_buffers_type bufs = response_.data(); std::string line( boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + response_.size()); if(line.find("\r\n\r\n")!=string::npos){std::cout << line;regex expression("^[\{](.*)[\}]$");cmatch what;if(regex_search(line.c_str(),what,expression)){//regex_match : 是对整个输入块的匹配,整个块如不匹配则不能成功for(unsigned int i=0;i<what.size();i++)cout<<"str match is :"<<what[i].str()<<endl;printf("\n----\n");}else{cout<<"Error Match"<<endl;}// zoomInfo_t zoomInfo ; PointInfo_t tmpPointInfo ; int sceneWidth ,sceneHeight,WatchZoneID ;// list<PointInfo_t> *tmpZoom = &zoomInfo.zoomPonitArray ;// cJSON *root = cJSON_Parse(what[0].str().c_str());// if(root==NULL){// return ;// }//// cJSON *tmp = cJSON_GetObjectItem(root,"sceneWidth") ;// if(tmp!=NULL){// sceneWidth = tmp->valueint ;// printf("width:%d \n",sceneWidth);// }else{// return ;// }// tmp = cJSON_GetObjectItem(root,"sceneHeight");// if(tmp!=NULL){// sceneHeight = tmp->valueint ;// printf("height:%d \n",sceneHeight);// }else{//// } } // Continue reading remaining data until EOF. boost::asio::async_read(socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&boostHttpclient_c::handle_read_content, this,boost::asio::placeholders::error));}else if (err != boost::asio::error::eof){ std::cout << "Error: " << err << "\n";}}int main(int argc, char* argv[]){ try { boost::asio::io_service io_service; boostHttpclient_c c(io_service, "192.168.1.46:8187", "/handle_post_request");// client c(io_service, "192.168.1.46:8187", "/"); io_service.run(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0;}
头文件:
#ifndef SRC_HTTPCLIENT_BOOSTHTTPCLIENT_H_#define SRC_HTTPCLIENT_BOOSTHTTPCLIENT_H_#include <iostream>#include <istream>#include <ostream>#include <string>#include <boost/asio.hpp>#include <boost/bind.hpp>#include <cJSON.h>#include <boost/regex.hpp>#include <string>#include <iostream>using boost::asio::ip::tcp;using namespace std;using namespace boost;class boostHttpclient_c{public:boostHttpclient_c(boost::asio::io_service& io_service, const std::string& server, const std::string& path);private: void handle_resolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator); void handle_connect(const boost::system::error_code& err); void handle_write_request(const boost::system::error_code& err); void handle_read_status_line(const boost::system::error_code& err); void handle_read_headers(const boost::system::error_code& err); void handle_read_content(const boost::system::error_code& err); tcp::resolver resolver_; tcp::socket socket_; boost::asio::streambuf request_; boost::asio::streambuf response_;};#endif /* SRC_HTTPCLIENT_BOOSTHTTPCLIENT_H_ */
参考文章:
如何使用SOCKET 发送HTTP1.1 GET POST请求包
http://blog.csdn.net/yc0188/article/details/4741871
0 0
- 使用boost做post/get请求开发笔记
- Android笔记---使用HttpClient发送POST和GET请求
- 【iOS开发-网络】使用NSURLSessionDataTask发送get和post请求
- iOS开发中 get请求、post请求
- 【iOS开发】 同步请求、异步请求、GET请求、POST请求
- 【C++】GET、POST网络请求boost.asio实现
- C++ Post/Get请求(Boost.Asio库)
- IOS开发笔记-NSURLConnection同步请求和异步请求以及get方法,post方法
- ios开发笔记—get请求和post请求简单代码
- iOS小明开发笔记(二十六) (同步、异步请求, GET、POST请求)
- iOS陆哥开发笔记(二十七) (同步、异步请求, GET、POST请求)
- iOS海哥开发笔记 (海哥原创,iOS 之同步请求、异步请求、GET请求、POST请求 )
- HttpURLConnection get post 方式请求 (笔记)
- java鬼混笔记:http get post 请求
- js原生ajax请求get post笔记
- IOS开发 HTTP相关GET/POST请求
- Android开发,post、get请求,线程框架
- iOS开发 GET、POST 请求方法
- STM32程序跳转后死机现象解决
- Another unnamed CacheManager already exists in the same VM
- 关于友盟QQ登录返回的信息
- 应用详情
- tiny6410驱动移植之触摸屏驱动
- 使用boost做post/get请求开发笔记
- iOS学习(3)——UIImageView
- html5的Web 存储功能做法
- Java设计模式——Observer(观察者)模式
- POJ 1753 Flip Game(暴力+搜索递归)
- HOOK 文件保护,隐藏 禁止访问
- ios 安卓锁屏
- Android 获取手机联系人
- photon入门