http_client.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // http_client.cpp
  3. // ~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #include <iostream>
  11. #include <istream>
  12. #include <ostream>
  13. #include <string>
  14. #include <boost/asio/ip/tcp.hpp>
  15. using boost::asio::ip::tcp;
  16. int main(int argc, char* argv[])
  17. {
  18. try
  19. {
  20. if (argc != 3)
  21. {
  22. std::cout << "Usage: http_client <server> <path>\n";
  23. std::cout << "Example:\n";
  24. std::cout << " http_client www.boost.org /LICENSE_1_0.txt\n";
  25. return 1;
  26. }
  27. boost::asio::ip::tcp::iostream s;
  28. // The entire sequence of I/O operations must complete within 60 seconds.
  29. // If an expiry occurs, the socket is automatically closed and the stream
  30. // becomes bad.
  31. s.expires_after(std::chrono::seconds(60));
  32. // Establish a connection to the server.
  33. s.connect(argv[1], "http");
  34. if (!s)
  35. {
  36. std::cout << "Unable to connect: " << s.error().message() << "\n";
  37. return 1;
  38. }
  39. // Send the request. We specify the "Connection: close" header so that the
  40. // server will close the socket after transmitting the response. This will
  41. // allow us to treat all data up until the EOF as the content.
  42. s << "GET " << argv[2] << " HTTP/1.0\r\n";
  43. s << "Host: " << argv[1] << "\r\n";
  44. s << "Accept: */*\r\n";
  45. s << "Connection: close\r\n\r\n";
  46. // By default, the stream is tied with itself. This means that the stream
  47. // automatically flush the buffered output before attempting a read. It is
  48. // not necessary not explicitly flush the stream at this point.
  49. // Check that response is OK.
  50. std::string http_version;
  51. s >> http_version;
  52. unsigned int status_code;
  53. s >> status_code;
  54. std::string status_message;
  55. std::getline(s, status_message);
  56. if (!s || http_version.substr(0, 5) != "HTTP/")
  57. {
  58. std::cout << "Invalid response\n";
  59. return 1;
  60. }
  61. if (status_code != 200)
  62. {
  63. std::cout << "Response returned with status code " << status_code << "\n";
  64. return 1;
  65. }
  66. // Process the response headers, which are terminated by a blank line.
  67. std::string header;
  68. while (std::getline(s, header) && header != "\r")
  69. std::cout << header << "\n";
  70. std::cout << "\n";
  71. // Write the remaining data to output.
  72. std::cout << s.rdbuf();
  73. }
  74. catch (std::exception& e)
  75. {
  76. std::cout << "Exception: " << e.what() << "\n";
  77. }
  78. return 0;
  79. }