简体   繁体   中英

POST request fails while using libcurl, C++

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

Error: CURLE_COULDNT_RESOLVE_HOST (6)

When I tested this POST request on postman it worked as expected. Also curl command curl --location --request POST 'https://postman-echo.com/post' works fine.

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

Run NSLOOKUP as suggested by @Andreas Wenzel

> 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

https://github.com/alexzk1/ed_highway/blob/master/utils/restclient.cpp

this works for many sites last 3-4 years. you can pick those 2 files only. It uses CURLOPT_POSTFIELDS for post.

Btw, in your code u're following redirects, are u sure website don't redirect you to non-existing link?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM