Get the App
SLTechnology News&Howtos  ›  Servers  › 

Network Communication lesson 4 A complete case of a Post request sent by C++

Shulou Source: shulou.com Published: 2022-06-03 03:26:21 09月22日 Update

Description

The current example uses boost asio library to send HTTP data message, and uses boost::asio::streambuf request stream to encapsulate the data message, at the end of the example.

The response packet is analyzed by string to obtain the json format packet.

# include

# include

# include

# include

Using namespace std

Using namespace boost::asio

Unsigned char ToHex (unsigned char x)

{

Return x > 9? X + 55: X + 48

}

Unsigned char FromHex (unsigned char x)

{

Unsigned char y

If (x > ='A'& & x ='a'& & x ='0' & & x > 4)

StrTemp + = ToHex ((unsigned char) str [I]% 16)

}

}

Return strTemp

}

Std::string UrlDecode (const std::string& str)

{

Std::string strTemp = ""

Size_t length = str.length ()

For (size_t I = 0; I < length; iTunes +)

{

If (str [I] ='+') strTemp + =''

Else if (str [I] = ='%')

{

Assert (I + 2 < length)

Unsigned char high = FromHex ((unsigned char) str[ + + I])

Unsigned char low = FromHex ((unsigned char) str[ + + I])

StrTemp + = high * 16 + low

}

Else strTemp + = str [I]

}

Return strTemp

}

Int HttpPost ()

{

/ / char szSrcBuffer [1024] = {"authorJson= {loginAccount:\" admin\ "} & parmJson= {code:\" SheBeiLiXianGaoJingShangChuan\ ", params: {id:\" 123456\ ", remarks:\" fire alarm\ ", time_alarm:\" 2017-1-1\ ", alarm_source:\" 192.168.1.11\ "}

Char szSrcBuffer [1024] = {"authorJson= {loginAccount:\" admin\ "} & parmJson= {code:\" SheBeiLiXianChaXun\ ", params: {}}"}

Std::string strUrlEnCodedBuffer = UrlEncode (szSrcBuffer)

Io_service iosev

Ip::tcp::socket socket (iosev)

Ip::tcp::endpoint ep (ip::address_v4::from_string ("192.168.0.88"), 8080)

Boost::system::error_code ec

Socket.connect (ep, ec)

If (ec) return-1

Boost::asio::streambuf request

Std::ostream request_stream & request)

Request_stream

Tags: Data examples messages formats analysis encapsulation cases networks network communications caching communications Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia Xiaomi MySQL vpn