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

标签 c json libcurl

我正在尝试弄清楚如何将 json 数据发送到 Web 服务。 json.phph y 只是一个打印所有 $_REQUEST 发送到脚本的 php。但最后我什么也没收到,我尝试发送 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;
}

最佳答案

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

关于c - 试图弄清楚如何通过 c 中的 lib curl 发送 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7896506/

相关文章:

c - 指向 const 静态数组的指针

java - Twitter 使用类似 twitter4j 的东西将 JSON 字符串保存到 Java 对象 (POJO) 中……?

c++ - 转换为未知类型

javascript - 用枚举写 JSON 的 Key

javascript - 按顺序获取 JSON 值并保持相应名称的顺序

c - libcurl C API > 使用 2MB 缓冲区以 block 的形式 POST 数据

c++ - 处理 linux 上的库依赖

c - 在Unix/Linux shell编程:the difference between > and >&

c++ - 哪种方法最适合从光驱中快速读取文件?

c - C 中的反转字符串函数