C++Curl添加和发送cookie

C++ Curl adding and sending cookies

本文关键字:cookie 添加 C++Curl      更新时间:2023-10-16

我一直在尝试编写一个发送post数据和COOKIES的程序。Cookie添加部分似乎没有正确添加Cookie。。。

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
int main(int argc, char *argv[])
{
  CURL *curl;
  CURLcode res;
  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headerlist=NULL;
  static const char buf[] = "Expect:";
  curl_global_init(CURL_GLOBAL_ALL);

   /* Fill in the nick field */ 
   curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "nick",
               CURLFORM_COPYCONTENTS, "nichnameofxxx",
               CURLFORM_END);
   /* Fill in the pass field */ 
   curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "pass",
               CURLFORM_COPYCONTENTS, "passwordofxxx",
               CURLFORM_END);
   /* Other fields like ID */ 
   curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "ProfileID",
               CURLFORM_COPYCONTENTS, "77820",
               CURLFORM_END);
  /* Fill in the submit field too, even if this is rarely needed */ 
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "submit",
               CURLFORM_COPYCONTENTS, "send",
               CURLFORM_END);

  curl = curl_easy_init();
  /* initalize custom header list (stating that Expect: 100-continue is not
     wanted */ 
  headerlist = curl_slist_append(headerlist, buf);
  //Cookies here... it's a part of the Header
  headerlist = curl_slist_append(headerlist, "Cookie: name=xxx; name2=xxx");
  if(curl) 
  {
     // what URL that receives this POST
     curl_easy_setopt(curl, CURLOPT_URL, "http://www.mything.org/index.php?id=log2");
     if ((argc == 2) && (!strcmp(argv[1], "noexpectheader")))
       curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
     curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
     res = curl_easy_perform(curl);
     curl_easy_cleanup(curl);
     curl_formfree(formpost);
     curl_slist_free_all (headerlist);
  }
  return 0;
}

欢迎任何帮助!

首先启动"cookie引擎",这是用完成的

 curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");

使用CURLOPT_COOKIE:设置COOKIE,而不是显式设置HTTP标头

 curl_easy_setopt(curl, CURLOPT_COOKIE, "name=xxx; name2=xxx;");