试图弄清楚如何通过lib curl在c中发送json数据

时间:2011-10-25 22:09:36

标签: c json libcurl

我正试图将json数据发送到Web服务。 json.phph y只是一个将所有$ _REQUEST发送到脚本的php。但在hehe end我没有收到任何东西,我尝试以urlenc格式发送表单,只是普通数据D: 我已经没有想法如何做到这一点。

#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[] = "Content-Type: application/json";

  curl_global_init(CURL_GLOBAL_ALL);
/* 
      curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "json", 
               CURLFORM_COPYCONTENTS, "reactantsJSON={\"O=O\":{\"N\":1}}&productsJSON=    [\"O=O\",\"[O]\"]&temperature=2273.15&pressure=101.325",
               CURLFORM_END);
*/
  curl = curl_easy_init();
  /* initalize custom header list (stating that Expect: 100-continue is not
 *      wanted */ 
  headerlist = curl_slist_append(headerlist, buf); 
  if(curl) {
    /* what URL that receives this POST */ 
    curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/json.php");
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl,CURLOPT_POST,1);
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,     "reactantsJSON%3d%7b%22O%3dO%22%3a%7b%22N%22%3a1%7d%7d%26productsJSON%3d%5b%22O%3dO%22%2c%22%5bO%5d%22%5d%26temperature%3d2273.15%26pressure%3d101.325"  );
//    curl_easy_setopt(curl,CURLOPT_POSTFIELDS, "reactantsJSON={\"O=O\":    {\"N\":1}}&productsJSON=[\"O=O\",\"[O]\"]&temperature=2273.15&pressure=101.325"  );
 //   if ( (argc == 2) && (!strcmp(argv[1], "noexpectheader")) )
      /* only disable 100-continue header if explicitly requested */ 
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
    res = curl_easy_perform(curl);

    /* always cleanup */ 
     curl_easy_cleanup(curl);

    /* then cleanup the formpost chain */ 
    curl_formfree(formpost);
    /* free slist */ 
    curl_slist_free_all (headerlist);
  }
  return 0;
}

1 个答案:

答案 0 :(得分:0)

你想要CURLOPT_HTTPPOST CURLOPT_POSTFIELDS,而不是两者。他们将发出两种不同的POST请求。