首页 > 解决方案 > 使用 libcurl、C++ 时 POST 请求失败

问题描述

TEST(ApiTest, TestPostMethod) {
  CURL *curl;
  CURLcode res;
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if (curl) {
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    std::string url = "https://postman-echo.com/post";
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
    struct curl_slist *headers = NULL;
    // curl_slist_append(headers, "HOST:  postman-echo.com");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    ASSERT_EQ(CURLE_OK, res);
  }
}

错误:CURLE_COULDNT_RESOLVE_HOST (6)

当我在邮递员上测试这个 POST 请求时,它按预期工作。curl 命令也 curl --location --request POST 'https://postman-echo.com/post' 可以正常工作。

Expected equality of these values:
  CURLE_OK
    Which is: 0
  res
    Which is: 6

按照@Andreas Wenzel 的建议运行 NSLOOKUP

> postman-echo.com
Server:     75.75.75.75
Address:    75.75.75.75#53

Non-authoritative answer:
Name:   postman-echo.com
Address: 3.210.84.203
Name:   postman-echo.com
Address: 52.22.211.29

标签: c++httppostlibcurl

解决方案


Sorry. I figured this out. My server on which I was run this has restrictions in connecting with outside world. Thanks everyone for looking into this.


推荐阅读