如何在此请求中使用 libcurl 并获得 json 服务器答案 c++?

问题描述

我有一些请求,我想在 libcurl 中使用它们。但我不知道该怎么做 那么我应该在像 "curl.get(dsds) curl.header("","")" 之类的代码中实现这个吗

curl "https://pterodactyl.file.properties/api/client/account" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer apikey' \
  -X GET \

curl "https://pterodactyl.file.properties/api/client/account/email" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer apikey' \
  -X PUT \
  -d '{
  "email": "example@xample.com","password": "Password"
}' 

curl "https://pterodactyl.file.properties/api/client/account/api-keys" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer apikey' \
  -X POST \
  -d '{
  "description": "Restricted IPs","allowed_ips": ["127.0.0.1","192.168.0.1"]
}' 

curl "https://pterodactyl.file.properties/api/client/account/api-keys/NWKMYMT2Mrav0Iq2" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer apikey' \
  -X DELETE \

解决方法

从网络下载东西的基本功能是

#include <iostream>
#include<curl/curl.h>
static size_t WriteCallback(void* contents,size_t size,size_t nmemb,void* userp)
{
    ((std::string*)userp)->append((char*)contents,size * nmemb);
    return size * nmemb;
}
std::string curlDownload(std::string link){
    CURL* curl;
    CURLcode res;
    std::string readBuffer;
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl,CURLOPT_URL,link.c_str());
        curl_easy_setopt(curl,CURLOPT_USERNAME,"myUserName"); //auth for userName
        curl_easy_setopt(curl,CURLOPT_PASSWORD,"Password"); //auth for password
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,WriteCallback);
        curl_easy_setopt(curl,CURLOPT_WRITEDATA,&readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return readBuffer;
}
int main() {

    std::string myLink = "https://pterodactyl.file.properties/api/client/account";
    std::cout << curlDownload(myLink) << std::endl; //this will print your request for authorization

    return 0;
}

为了放置东西,你需要这样的东西,当然还有你自己的数据

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers,client_id_header);
    headers = curl_slist_append(headers,"Content-Type: application/json");

    curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers); 
    curl_easy_setopt(curl,request_url);  
    curl_easy_setopt(curl,CURLOPT_CUSTOMREQUEST,"PUT"); /* !!! */

    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,json_struct); /* data goes here */

    res = curl_easy_perform(curl);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}

更多关于 put herehere

更多关于 CURLOPT here 这将返回带有给定输出的 std::string,例如您的 json。然后你需要解析它。

为了安装 libcurl for windows,你可以关注 this 线程

对于 linux cmake,您应该在 cmake 文件旁边添加

set(CURL_LIBRARY "-lcurl")
find_package(CURL REQUIRED)
include_directories(... ${CURL_INCLUDE_DIR})
target_link_libraries(... $(CURL_LIBRARIES))