C++ Curl添加和发送cookie

4 c++ cookies post http

我一直在努力编写一个发送帖子数据和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;
}
Run Code Online (Sandbox Code Playgroud)

欢迎任何帮助!

bro*_*ekk 11

首先启动"cookie引擎",这是通过以下方式完成的:

 curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
Run Code Online (Sandbox Code Playgroud)

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

 curl_easy_setopt(curl, CURLOPT_COOKIE, "name=xxx; name2=xxx;");
Run Code Online (Sandbox Code Playgroud)