HttpProbeImpl.cpp 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "RestfulFunc.h"
  2. #include <iostream>
  3. #include "cpprest/uri.h"
  4. #include "cpprest/http_client.h"
  5. using namespace utility; // Common utilities like string conversions
  6. using namespace web; // Common features like URIs.
  7. using namespace web::http; // Common HTTP functionality
  8. using namespace web::http::client; // HTTP client features
  9. using namespace concurrency::streams; // Asynchronous streams
  10. int HttpProbe(const std::string& url, std::string& out_msg, uint32_t wait_max_secs)
  11. {
  12. int result(-1);
  13. out_msg.clear();
  14. if (url.empty()) {
  15. out_msg = "invalid param";
  16. result = -3;
  17. } else {
  18. utility::string_t response_content;
  19. utf8string utf8_response_content;
  20. const pplx::task<void> request_task = pplx::task<http_response>([&]() {
  21. http_client_config config;
  22. if (wait_max_secs != (uint32_t)(-1)) {
  23. config.set_timeout(utility::seconds(wait_max_secs));
  24. }
  25. config.set_validate_certificates(false);
  26. http_client client(url, config);
  27. return client.request(methods::GET);
  28. }).then([&](http_response response) {
  29. ucout << U(">>>>>> response status: ") << response.status_code() << std::endl;
  30. result = response.status_code();
  31. });
  32. try {
  33. request_task.wait();
  34. } catch (const std::exception& e) {
  35. out_msg = e.what();
  36. std::cout << "exception occurs: " << e.what() << "\n\n";
  37. if (strstr(e.what(), "12002") != nullptr || strstr(e.what(), "Request canceled by user") != nullptr) {
  38. result = -2;
  39. } else if (strstr(e.what(), "URI must contain a hostname") != nullptr) {
  40. result = -3;
  41. } else {
  42. result = -1;
  43. }
  44. }
  45. }
  46. return result;
  47. }