Performs an HTTP request against httpbin.cpp.al and prints request & response
| 131 | |
| 132 | // Performs an HTTP request against httpbin.cpp.al and prints request & response |
| 133 | int main(int argc, char** argv) |
| 134 | { |
| 135 | try |
| 136 | { |
| 137 | // Check command line arguments. |
| 138 | if(argc != 2) |
| 139 | { |
| 140 | std::cerr << |
| 141 | "Usage: http-client-method <method> \n" << |
| 142 | "Example:\n" << |
| 143 | " http-client-method get\n" << |
| 144 | " http-client-method post\n"; |
| 145 | return EXIT_FAILURE; |
| 146 | } |
| 147 | |
| 148 | for (char * c = argv[1]; *c != '\0'; c++) |
| 149 | *c = static_cast<char>(std::tolower(*c)); |
| 150 | beast::string_view method{argv[1]}; |
| 151 | |
| 152 | // The io_context is required for all I/O |
| 153 | net::io_context ioc; |
| 154 | |
| 155 | // These objects perform our I/O |
| 156 | tcp::resolver resolver(ioc); |
| 157 | beast::tcp_stream stream(ioc); |
| 158 | |
| 159 | // Look up the domain name |
| 160 | auto const results = resolver.resolve("httpbin.cpp.al", "http"); |
| 161 | |
| 162 | // Make the connection on the IP address we get from a lookup |
| 163 | stream.connect(results); |
| 164 | |
| 165 | |
| 166 | // Set up an HTTP GET request message |
| 167 | http::request<http::string_body> req; |
| 168 | req.set(http::field::host, "httpbin.cpp.al"); |
| 169 | req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); |
| 170 | |
| 171 | |
| 172 | // This buffer is used for reading and must be persisted |
| 173 | beast::flat_buffer buffer; |
| 174 | |
| 175 | // Declare a container to hold the response |
| 176 | http::response<http::dynamic_body> res; |
| 177 | |
| 178 | if (method == "get") |
| 179 | do_get(stream, req, buffer, res); |
| 180 | else if (method == "head") |
| 181 | do_head(stream, req, buffer, res); |
| 182 | else if (method == "patch") |
| 183 | do_patch(stream, req, buffer, res); |
| 184 | else if (method == "put") |
| 185 | do_put(stream, req, buffer, res); |
| 186 | else if (method == "post") |
| 187 | do_post(stream, req, buffer, res); |
| 188 | else if (method == "delete") |
| 189 | do_delete(stream, req, buffer, res); |
| 190 | else |