Идентификатор в пути в C++
Шаблон "/users/" с числом в конце означает, что
идентификатор выбирает запись.
Строку адреса собирают заранее, подставляя нужное
число в литерал. Пусть требуется пользователь с номером
2 - после чтения тела достаточно полей
id и name:
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>
size_t writeBody(
char* ptr,
size_t size,
size_t nmemb,
void* userdata
) {
auto* body = static_cast<std::string*>(userdata);
body->append(ptr, size * nmemb);
return size * nmemb;
}
int main() {
int userId = 2;
std::string address =
"https://jsonplaceholder.typicode.com/users/"
+ std::to_string(userId);
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
std::string body;
curl_easy_setopt(curl, CURLOPT_URL, address.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeBody);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
nlohmann::json user = nlohmann::json::parse(body);
std::cout << user.at("id").get<int>() << "\n";
std::cout << user.at("name").get<std::string>() << "\n";
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return res == CURLE_OK ? 0 : 1;
}
Тот же прием работает для другого числа: меняется
только переменная идентификатора. Значение 3
в пути дает третью учебную запись:
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>
size_t writeBody(
char* ptr,
size_t size,
size_t nmemb,
void* userdata
) {
auto* body = static_cast<std::string*>(userdata);
body->append(ptr, size * nmemb);
return size * nmemb;
}
int main() {
int userId = 3;
std::string address =
"https://jsonplaceholder.typicode.com/users/"
+ std::to_string(userId);
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
std::string body;
curl_easy_setopt(curl, CURLOPT_URL, address.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeBody);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
nlohmann::json user = nlohmann::json::parse(body);
std::cout << user.at("name").get<std::string>() << "\n";
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return res == CURLE_OK ? 0 : 1;
}