httplib could not establish connection

1.1k views Asked by At

I'm working on C++ software that has to communicate with an API via REST API. I'm using httplib. I do the next:

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";
}

It responds with this error message: Could not establish connection If I type the given URL into the browser, it corresponds correctly. I tried to give the port number (443) into the constructor of the SSLClient, but I don't have any different results. I have OpenSSL on my PC, and I included the httplib like this:

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

What should I do to achieve my goal?

Thank you in advance.

1

There are 1 answers

0
SeanTolstoyevski On

It seems it can only work with host part when parsing URLs.
I had the same issue with MinGW64 (gcc 13 & cpp-httplib 0.12.6).

If you only need the host part of a URL, you can use spec-compliant libraries such as the ada libraries.

The following code is able to successfully download the homepage of "google.com" and write it to a file.

compile command (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;
}