我在 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 许可协议
Curl 命令有一个选项 –libcurl 。它应该可以帮助您找出要使用的正确 libcurl 代码。
将此选项与文件名一起添加到工作 Curl 命令的末尾,Curl 将输出 Curl 命令的工作 libcurl c 示例。
使用 -lcurl 选项编译输出的代码。
下面是我用来将 JSON 从 c++ 发布到 node.js 的 libcurl 代码示例。
Node.js (Express) 接收 JSON 为: