如何通过 get 请求使用 curl in 获取站点的 https 响应?

How can I get https response of a site using curl in via get request?

我有执行该操作的代码,但为什么它不起作用:

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

int main()
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
  curl_easy_setopt(curl, CURLOPT_URL, "https://curl.haxx.se/libcurl/c/url2file.html");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout);
  res = curl_easy_perform(curl);
      if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
}
curl_easy_cleanup(curl);
return 0;
}

给出输出:

curl_easy_perform() failed: SSL peer certificate or SSH remote key was not OK

但是当我在 cmd 中执行 'curl https://curl.haxx.se/libcurl/c/url2file.html' 时,它成功给出了响应。

我从 Postman 那里得到了这段代码,并进行了一些编辑。 我的目的是将网站的响应打印到标准输出。

'Get' 请求在 Postman 上运行良好,但为什么它在 c 中的 libcurl 上运行不佳。 我怎么解决这个问题 ? 我是 libcurl 的新手,找不到足够好的信息,那么你有什么建议?

我猜这是错误号 60? (记录here

这意味着 libcurl 使用的 CA 证书无法验证来自 curl.haxx.se 的服务器证书 - 如果您启用 CURLOPT_VERBOSE,您可以看到它使用的 CA 证书路径。您可能必须将其指向特定路径。

您的代码还使用了很多您可以删除的多余选项:

curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");

这是默认值

curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");

只有当您指定 "URLs" 时没有方案才有趣,而您没有!

struct curl_slist *headers = NULL;
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

这没有效果。

curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout);

无论如何这是默认值。