c++ httplib无法建立连接

6mzjoqzu  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(703)

我正在开发C++软件,它必须通过REST API与API进行通信。我用的是httplib。我做下一个:

  1. httplib::SSLClient cli("https://www.google.com");
  2. httplib::Result res = cli.Get("/doodles");
  3. if (res && res->status == 200)
  4. {
  5. std::cout << res->body << "\n";
  6. }
  7. else
  8. {
  9. auto err = res.error();
  10. std::cout << httplib::to_string(err) << "\n";
  11. }

它会返回以下错误消息:Could not establish connection如果我在浏览器中键入给定的URL,它就正确对应了。我试图将端口号(443)输入到SSLClient的构造函数中,但没有得到任何不同的结果。我的PC上有OpenSSL,我包括了httplib,如下所示:

  1. #define CPPHTTPLIB_OPENSSL_SUPPORT
  2. #include <httplib\httplib.h>

我应该做些什么来实现我的目标?
先谢谢你。

w1e3prcc

w1e3prcc1#

它似乎只能在解析URL时使用host部分。
我在MinGW 64(gcc 13 & cpp-htplib 0.12.6)上遇到了同样的问题。
如果只需要URL的host部分,可以使用符合规范的库,例如ada库。
下面的代码可以成功下载“www.example.com”的主页google.com并写入文件。
编译命令(Windows,MinGW 64):
g++ x1.cpp -I. -static -lcrypt32 -lwinmm -lssl -lcrypto -lws2_32

  1. #define WIN32_LEAN_AND_MEAN
  2. #define CPPHTTPLIB_OPENSSL_SUPPORT
  3. #include <fstream>
  4. #include <httplib.h>
  5. #include <iostream>
  6. #include <string>
  7. bool downloadFile(const std::string &url, const std::string &path) {
  8. httplib::SSLClient client{url};
  9. client.enable_server_certificate_verification(false);
  10. std::ofstream file(path, std::ios::binary | std::ios::trunc);
  11. if (!file) { return false; }
  12. auto response =
  13. client.Get("/", [&](const char *data, size_t data_length) -> bool {
  14. file.write(data, data_length);
  15. return true;
  16. });
  17. return response;
  18. }
  19. int main() {
  20. std::string url = "www.google.com";
  21. std::string path = "downloaded_file.txt";
  22. if (downloadFile(url, path)) {
  23. std::cout << "File downloaded successfully." << std::endl;
  24. } else {
  25. std::cout << "Failed to download the file." << std::endl;
  26. }
  27. return 0;
  28. }
展开查看全部

相关问题