嵌套的 libcurl 请求 C++

问题描述

我的问题是我将如何执行嵌套的 curl 请求,因为我当前的代码是这样的并且不起作用。我无法工作,因为我可以看到请求发送到我的服务器,并且只有一个请求是 GET 请求。

#include <curl/curl.h>
#include <iostream>

int rad = rand() % 100000;
std::string agent_name = "https://127.0.0.1:443/agent/" + std::to_string(rad);


int main(int argc,char *argv[])
{
  CURLcode res;
  CURL *curl;

  curl = curl_easy_init();
  curl_easy_setopt(curl,CURLOPT_BUFFERSIZE,102400L);
  curl_easy_setopt(curl,CURLOPT_URL,"https://127.0.0.1:443/");
  curl_easy_setopt(curl,CURLOPT_nopROGRESS,1L);
  curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0L);
  curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,CURLOPT_FTP_SKIP_PASV_IP,CURLOPT_TCP_KEEPALIVE,1L);

  res = curl_easy_perform(curl);
  
  if (res == CURLE_OK) {
    long response_code;
    curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&response_code);
    if (response_code == 200)
    {
      std::cout << "Hello";
      CURLcode ret;
      CURL *hnd;

      hnd = curl_easy_init();
      curl_easy_setopt(hnd,102400L);
      curl_easy_setopt(hnd,agent_name);
      curl_easy_setopt(hnd,1L);
      curl_easy_setopt(hnd,0L);
      curl_easy_setopt(hnd,CURLOPT_CUSTomrEQUEST,"POST");
      curl_easy_setopt(hnd,1L);

      ret = curl_easy_perform(hnd);

      curl_easy_cleanup(hnd);
      hnd = NULL;

    }
    else { }
  }
  curl_easy_cleanup(curl);
  curl = NULL;

}

这会将 Hello 打印到标准输出,但不会运行 curl POST 请求,因此如何执行嵌套的 curl 请求。

编辑:我尝试删除 if 语句。所以我的问题是如何做两个 libcurl 请求

解决方法

您的 curl_easy_perform(hnd) 返回 3

通过cURL

CURLE_URL_MALFORMAT (3)

网址格式不正确。

您必须传递 char * 而不是 std::string(请参阅 here):

curl_easy_setopt(hnd,CURLOPT_URL,agent_name.c_str());