diff --git a/client_http.hpp b/client_http.hpp index a03afa0..080e5a3 100644 --- a/client_http.hpp +++ b/client_http.hpp @@ -37,20 +37,37 @@ namespace SimpleWeb { template class ClientBase { public: + class Content : public std::istream { + friend class ClientBase; + public: + size_t size() { + return streambuf.size(); + } + /// Convenience function to return std::string. Note that the stream buffer is emptied when this functions is used. + std::string string() { + std::stringstream ss; + ss << rdbuf(); + return ss.str(); + } + private: + asio::streambuf &streambuf; + Content(asio::streambuf &streambuf): std::istream(&streambuf), streambuf(streambuf) {} + }; + class Response { friend class ClientBase; friend class Client; public: std::string http_version, status_code; - std::istream content; + Content content; CaseInsensitiveMultimap header; private: asio::streambuf content_buffer; - Response(): content(&content_buffer) {} + Response(): content(content_buffer) {} }; class Config { diff --git a/http_examples.cpp b/http_examples.cpp index d211661..7aaa324 100644 --- a/http_examples.cpp +++ b/http_examples.cpp @@ -184,7 +184,7 @@ int main() { // synchronous request examples auto r1=client.request("GET", "/match/123"); - cout << r1->content.rdbuf() << endl; + cout << r1->content.rdbuf() << endl; // Alternatively, use the convenience function r1->content.string() string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}"; auto r2=client.request("POST", "/string", json_string); diff --git a/https_examples.cpp b/https_examples.cpp index 8719c9a..4d7dd8d 100644 --- a/https_examples.cpp +++ b/https_examples.cpp @@ -181,7 +181,7 @@ int main() { // synchronous request examples auto r1=client.request("GET", "/match/123"); - cout << r1->content.rdbuf() << endl; + cout << r1->content.rdbuf() << endl; // Alternatively, use the convenience function r1->content.string() string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}"; auto r2=client.request("POST", "/string", json_string); diff --git a/server_http.hpp b/server_http.hpp index bfbbb22..95aaf8e 100644 --- a/server_http.hpp +++ b/server_http.hpp @@ -126,6 +126,7 @@ namespace SimpleWeb { size_t size() { return streambuf.size(); } + /// Convenience function to return std::string. Note that the stream buffer is emptied when this functions is used. std::string string() { std::stringstream ss; ss << rdbuf(); diff --git a/tests/io_test.cpp b/tests/io_test.cpp index 97b10e6..4db55f2 100644 --- a/tests/io_test.cpp +++ b/tests/io_test.cpp @@ -70,6 +70,13 @@ int main() { assert(output.str()=="A string"); } + { + stringstream output; + auto r=client.request("POST", "/string", "A string"); + assert(SimpleWeb::status_code(r->status_code)==SimpleWeb::StatusCode::success_ok); + assert(r->content.string()=="A string"); + } + { stringstream output; auto r=client.request("POST", "/string2", "A string");