2020/10/27

http PUT request

最清楚簡單的 example 在 這裡
還有這一篇 有詳細的 example 和 server response 的解釋。

這一篇 有說,如何用 curl 下 PUT request

使用 Boost asio 來發。這篇 的回答有比較詳細的(但是是 POST request),可以參考。
這一個 pdf 中也有 tcp stream 的寫法:
tcp::iostream s("www.boost.org", "http");

s.expires_from_now(std::chrono::seconds(60));

s << "GET / HTTP/1.0\r0.2cm\n";
s << "Host: www.boost.org\r\n";
s << "Accept: */*\r\n";
s << "Connection: close\r\n\r\n";
And then receive and process the response:
std::string header;
while (std::getline(s, header) && header != "\r")
 std::cout << header << "\n";
std::cout << s.rdbuf();
If at any time there is an error, the tcp::iostream class’s error() member function may be used to determine the reason for failure:
if (!s)
{
 std::cout << "Socket error: " << s.error().message() << "\n";
 return 1;
}

所以用 boost::asio 來寫一個 PUT request: boostasio.cpp
#include <boost/asio.hpp>

int main()
{
	boost::asio::ip::tcp::iostream s("127.0.0.1","8123");
	s << "PUT /customers/23 HTTP/1.1\n";
	s << "Host: 127.0.0.1\r\n";
	s << "Content-length: 0\r\n";
	s << "\r\n";
//	s << std::flush;
}
build command:
g++ boostasio.cpp -lboost_system -lpthread

配合 json 作為 PUT 的 body 要參考這裡:
PUT /echo/put/json HTTP/1.1
Accept: application/json
Content-Type: application/json
Content-Length: 85
Host: reqbin.com

{
  "Id": 12345,
  "Customer": "John Smith",
  "Quantity": 1,
  "Price": 10.00
}

如果要看 server 的 reponse,這一篇 有簡單的 example,
就是..
ip::tcp::iostream stream;
stream.expires_from_now(boost::posix_time::seconds(60));
stream.connect("www.boost.org", "http");
stream << "GET /LICENSE_1_0.txt HTTP/1.0\r\n";
stream << "Host: www.boost.org\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n\r\n";
stream.flush();
std::cout << stream.rdbuf();

沒有留言:

張貼留言