HttpclientDemo.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <iostream>
  2. #include <fstream>
  3. // 3rd_party 消除min max函数冲突
  4. #undef min
  5. #undef max
  6. #define NOMINMAX
  7. #include "json.hpp"
  8. using json = nlohmann::json;
  9. #define CPPHTTPLIB_OPENSSL_SUPPORT
  10. #include "httplib.h"
  11. int main()
  12. {
  13. json httpJson;
  14. httplib::Client cli("https://www.okx.com");
  15. // cli.set_proxy_basic_auth("user", "pass"); //匿名代理不需要设置认证信息
  16. cli.set_proxy("127.0.0.1", 1024);
  17. // 设置Chrome浏览器User-Agent
  18. httplib::Headers headers = {
  19. { "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36" }
  20. };
  21. httplib::Params params;
  22. params.emplace("instId", "BTC-USDT");
  23. params.emplace("bar", "1m");
  24. params.emplace("limit", "100");
  25. for (int i = 0; i < 50; i++) {
  26. auto res = cli.Get("/api/v5/market/candles", params, headers);
  27. if (res->status == 200) {
  28. json kLine;
  29. try {
  30. kLine = json::parse(res->body);
  31. std::string code = kLine["code"];
  32. std::cout << "num: " << i << "dataSize:" << kLine["data"].size() << "\n" << std::endl;
  33. // std::cout << "dataSize:\n" << kLine["data"].size() << std::endl;
  34. //std::cout << "Parsed JSON:\n" << kLine.dump(4) << std::endl;
  35. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  36. }
  37. catch (const std::exception& e) {
  38. throw std::runtime_error("Json解析错误: " + std::string(e.what()) + "!");
  39. break;
  40. }
  41. }
  42. }
  43. }