#c #curl #libcurl
#c #curl #libcurl
Вопрос:
У меня возникла проблема с передачей значения переменной в текст сообщения при использовании libcurl. Вот мой код :
#include "curl/curl.h"
char *fullname ="morpheus";
char *role = "leader";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, "https://reqres.in/api/users");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: text/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
const char *data = "{"name": "${fullname}" ,"job":"${role}"}";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt);
res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
Комментарии:
1. Вам нужно будет создать строку.
sprintf
будет работать.
Ответ №1:
Вы передаете имя самой переменной в виде строки. Вы должны объединить значение, а не имя.
#include "curl/curl.h"
char *fullname ="morpheus";
char *role = "leader";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, "https://reqres.in/api/users");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: text/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
char *data = "{"name":";
strcat(data, fullname);
strcat(data, ","job":");
strcat(data, role);;
strcat(data, ""}");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt);
res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
Это, конечно, не самый чистый способ, но он сработает.
Комментарии:
1. Спасибо за ответ. Это действительно тренировка. Также я хотел спросить, как мне распечатать ответ из POST-вызова и как мне использовать конкретные пары ключ-значение, например, для ex ( «success»:»true», «id»:»ABC1X») Я хочу напечатать только (id: abc1x). как я могу с этим справиться.