httplib 无法建立连接

问题描述 投票:0回答:2

我正在开发 C++ 软件,该软件必须通过 REST API 与 API 进行通信。我正在使用httplib。我做下一步:

httplib::SSLClient cli("https://www.google.com");
httplib::Result res = cli.Get("/doodles");
if (res && res->status == 200)
{
    std::cout << res->body << "\n";
}
else
{
    auto err = res.error();
    std::cout << httplib::to_string(err) << "\n";
}

它会响应以下错误消息:

Could not establish connection
如果我在浏览器中输入给定的 URL,它会正确对应。 我尝试将端口号(443)赋予
SSLClient
的构造函数,但没有任何不同的结果。 我的电脑上有 OpenSSL,并且我包含了 httplib,如下所示:

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

我应该做什么来实现我的目标?

提前谢谢您。

c++ client httplib
2个回答
1
投票

解析 URL 时似乎只能与

host
部分一起工作。
我对 MinGW64 (gcc 13 & cpp-httplib 0.12.6) 也有同样的问题。

如果您只需要 URL 的

host
部分,则可以使用符合规范的库,例如 ada 库。

以下代码能够成功下载“google.com”的主页并将其写入文件。

编译命令(Windows、MinGW64):

g++ x1.cpp -I. -static -lcrypt32 -lwinmm -lssl -lcrypto -lws2_32

#define WIN32_LEAN_AND_MEAN

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <fstream>
#include <httplib.h>
#include <iostream>
#include <string>

bool downloadFile(const std::string &url, const std::string &path) {
  httplib::SSLClient client{url};
  client.enable_server_certificate_verification(false);

  std::ofstream file(path, std::ios::binary | std::ios::trunc);
  if (!file) { return false; }

  auto response =
      client.Get("/", [&](const char *data, size_t data_length) -> bool {
        file.write(data, data_length);
        return true;
      });

  return response;
}

int main() {
  std::string url = "www.google.com";
  std::string path = "downloaded_file.txt";

  if (downloadFile(url, path)) {
    std::cout << "File downloaded successfully." << std::endl;
  } else {
    std::cout << "Failed to download the file." << std::endl;
  }

  return 0;
}

0
投票

使用 httplib::Client 而不是 httplib::SSLClient。此外,这个特定的请求会导致重定向,因此您需要添加 cli.set_follow_location(true) 才能获取商品。

    httplib::Client cli("https://www.google.com");

    cli.set_follow_location(true);

    httplib::Result res = cli.Get("/doodles");

    if (res && res->status == 200)
    {
        std::cout << res->body << "\n";
    }
    else
    {
        auto err = res.error();
        std::cout << httplib::to_string(err) << "\n";
    }
© www.soinside.com 2019 - 2024. All rights reserved.