在 C 中使用 cURL 的 JSON 请求

新手上路,请多包涵

我在 cURL 中有以下命令,这在终端中运行良好。

curl --insecure -X POST --data "username=testuser&password=12345" https://m360-prototype.herokuapp.com/sessions.json

这个 json api 发送了一些参数,例如 "status":{"code":200,"message":"OK"}

现在我希望我的 c++ 程序执行它。我之前已经设置并使用了 cURL 来从 ftp 示例上传和下载 ftp。但我没有找到任何例子来做到这一点。

我想知道如何将用户名和密码参数传递给 json api,并从中获得响应。

这是我在网上找到的一些代码中尝试过的,它没有用。

 struct curl_slist *headers=NULL; // init to NULL is important

headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");

curl = curl_easy_init();
if(curl) {
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_URL, "https://m360-prototype.herokuapp.com/sessions.json");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=testuser&password=12345");

    curl_easy_setopt(curl, CURLOPT_HTTPGET,1);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    res = curl_easy_perform(curl);

    if(CURLE_OK == res) {
        char *ct;
        /* ask for the content-type */
        res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
        if((CURLE_OK == res) && ct)
            printf("We received Content-Type: %s\n", ct);
    }
}

我如何从网络上获得响应?我知道它将是字符串的形式,我有足够的能力来解析它。

我正在查找传递给终端上执行的 curl 命令的所有参数(–insecure、-X、POST、–data),以便对我必须做什么一无所知。

我是一名图形程序员 :) 不太擅长使用 Web 服务。我会很感激任何帮助。

原文由 2am 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 793
1 个回答

Curl 命令有一个选项 –libcurl 。它应该可以帮助您找出要使用的正确 libcurl 代码。

将此选项与文件名一起添加到工作 Curl 命令的末尾,Curl 将输出 Curl 命令的工作 libcurl c 示例。

curl –insecure -X POST –data “username=testuser&password=12345” https://m360-prototype.herokuapp.com/sessions.json –libcurl test.cpp

使用 -lcurl 选项编译输出的代码。

g++ -lcurl test.cpp -o testcurl

下面是我用来将 JSON 从 c++ 发布到 node.js 的 libcurl 代码示例。

   CURLcode ret;
  CURL *hnd;
  struct curl_slist *slist1;
  std::string jsonstr = "{\"username\":\"bob\",\"password\":\"12345\"}";

  slist1 = NULL;
  slist1 = curl_slist_append(slist1, "Content-Type: application/json");

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_URL, "https://example.com/");
  curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
  curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, jsonstr.c_str());
  curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.38.0");
  curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  ret = curl_easy_perform(hnd);

  curl_easy_cleanup(hnd);
  hnd = NULL;
  curl_slist_free_all(slist1);
  slist1 = NULL;

Node.js (Express) 接收 JSON 为:

{ 用户名:’bob’,密码:’12345’ }

原文由 Rahim Khoja 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题