Cross-platform C++/boost/asio simple HTTP POST request client model

Source: Internet
Author: User
Tags http post

As an echo, write a C + + version of the synchronous HTTP Post client feature, if you need a pure C version, step here

Linux Pure C Simple HTTP POST request client model

Explain the basic HTTP POST protocol

    • Implementation of TCP message boundaries through \ r \ n
    • The first paragraph of each request POST/A.B http/1.1
      • The method of POST HTTP, and the most commonly used get, of course there are several other, skipped
      • /A.B requested page path, for example, if it is the homepage, the most common is/
      • http/1.1 HTTP protocol version number, legend has been out of 2, there are magic Google out to replace the HTTP protocol spdy
    • This information indicates that this is a form
      • content-type:application/x-www-form-urlencoded
    • This information indicates the length of the package of the HttpPost, not required
      • Content-length:12
    • And then there's a blank line, which represents the next package.

Just a request, it's easier to talk about the response.

    • Response Content http/1.1 OK
      • 200 is the status in the transmission, 404 didn't find it, wait!
      • http/1.1 indicates the version number of the HTTP
      • Of course, if Baotou can also exist, it is not introduced here
      • Then there is a blank line, split is the package body

All right, just go to the code.

#include <iostream>#include<istream>#include<ostream>#include<string>#include<boost/asio.hpp>usingboost::asio::ip::tcp;usingSTD::string;intPostConst string& Host,Const string& Port,Const string& Page,Const string& Data,string&reponse_data) {  Try{Boost::asio::io_service io_service; //if the Io_service exists for reuse    if(io_service.stopped ()) Io_service.reset (); //get all IPs under the domain name from DNStcp::resolver Resolver (io_service);    Tcp::resolver::query Query (host, port); Tcp::resolver::iterator Endpoint_iterator=resolver.resolve (query); //attempt to connect to one of these IPs until successfultcp::socket socket (io_service);     Boost::asio::connect (socket, endpoint_iterator); //Form the request. We Specify the "Connection:close" header so, the//server would close the socket after transmitting the response. this would//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.0\r\n"; Request_stream<<"Host:"<< Host <<":"<< Port <<"\ r \ n"; Request_stream<<"Accept: */*\r\n"; Request_stream<<"content-length:"<< data.length () <<"\ r \ n"; Request_stream<<"content-type:application/x-www-form-urlencoded\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 would automatically//grow to accommodate the entire line. The growth is 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::stringhttp_version; Response_stream>>http_version; unsignedintStatus_code; Response_stream>>Status_code; STD::stringStatus_message;    Std::getline (Response_stream, status_message); if(!response_stream | | http_version.substr (0,5) !="http/") {Reponse_data="Invalid Response"; return-2; }    //If the server returns a non-200 is considered to be wrong, does not support 301/302 and other jumps    if(Status_code! = $) {Reponse_data="Response returned with status code! =" ; returnStatus_code; }    //The legendary Baotou can be read down.STD::stringheader; Std::vector<string>headers;  while(Std::getline (Response_stream, header) && header! ="\ r") Headers.push_back (header); //Read all the rest of the data as the package bodyBoost::system::error_code error;  while(Boost::asio::read (socket, response, Boost::asio::transfer_at_least (1, error)) {}//Response with Data    if(Response.size ()) {Std::istream Response_stream (&response); Std::istreambuf_iterator<Char>EOS; Reponse_data=string(std::istreambuf_iterator<Char>(Response_stream), EOS); }    if(Error! =boost::asio::error::eof) {Reponse_data=Error.message (); return-3; }  }  Catch(std::exception&e) {reponse_data=E.what (); return-4; }  return 0;}intMainintargcChar*argv[]) {  stringHost ="127.0.0.1"; stringPort =" the"; stringpage ="/auth/login"; stringdata ="user_name=linbc&password=a"; stringReponse_data; intRET =Post (host, port, page, data, reponse_data); if(Ret! =0) Std::cout<<"Error_code:"<< ret <<Std::endl; Std::cout<< Reponse_data <<Std::endl; return 0;}

Compile it.

g++ Post.cc-std=c++11-pthread-lboost_system

Cross-platform C++/boost/asio simple HTTP POST request client model

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.