使用libcurl和jsoncpp发布到API并获得响应(C++)

m1m5dgzv  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(179)

我不完全确定我应该做什么来将数据POST到API(5sim.net)。我现在使用的是一个read回调,如下所示:
https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
我的问题类似于Using libCurl and JsonCpp to parse from https webserver,但我需要先发送信息以获得响应。
当我没有为API的这一部分发送数据时,我已经在接受数据时使一切工作正常:
第一个
将数据添加到有效负载会导致请求失败。
我尝试使用的API的下一部分需要授权。下面是我所拥有的,但是当我发送它时,curl_easy_perform()没有返回CURLE_OK(第一个curl_easy_perform()调用):
第一个
我只是需要一些指导,如何张贴数据,并得到一个响应,这是不工作。
我所要做的就是将带有JSON数据的POST发送到一个API并获得响应,解析该响应,然后将其作为一个结构返回。
API文档链接
更新:这是我的代码现在,不幸的是它返回HTTP GET错误404,不确定是否有什么我应该修复...

FiveSimUserInformation Get5SimUserInformation(std::string APIKey)
    {
        std::string Url = "https://5sim.net/v1/user/profile/";
    
        std::cout << colors::bright_yellow << "[!] " << colors::white << "Querying 5sim user balance information from " << Url << ".\n";
        if (curl_global_init(CURL_GLOBAL_ALL) == CURLE_OK)
        {
            CURL* Curl = curl_easy_init();
    
    
            std::string Request1 = R"("Authorization": "Bearer )" + APIKey + R"(")";
            std::string Request2 = R"("application/json")";
    
            curl_easy_setopt(Curl, CURLOPT_URL, Url.c_str());
            curl_easy_setopt(Curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
            curl_easy_setopt(Curl, CURLOPT_TIMEOUT, 10);
            curl_easy_setopt(Curl, CURLOPT_FOLLOWLOCATION, TRUE);
            std::unique_ptr<std::string> HttpData(new std::string());
    
            curl_easy_setopt(Curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    
            curl_easy_setopt(Curl, CURLOPT_WRITEDATA, HttpData.get());
    
            LONG HttpCode(NULL);
            curl_slist* List = nullptr;
            List = curl_slist_append(List, Request1.c_str());
            List = curl_slist_append(List, Request2.c_str());
            curl_easy_setopt(Curl, CURLOPT_HTTPHEADER, List);
    
            curl_easy_perform(Curl);
            curl_easy_getinfo(Curl, CURLINFO_RESPONSE_CODE, &HttpCode);
            curl_easy_cleanup(Curl);
    
            if (HttpCode == 200)
            {
    
                std::cout << colors::bright_yellow << "[!] " << colors::white << "Data recived: \n" << *HttpData.get() << '\n';
    
                std::cout << colors::bright_green << "[!] " << colors::bright_yellow << "HTTP GET attempt respose code: " << HttpCode << "\n";
    
                    Json::Value RecivedData;
                    Json::Reader Reader;
                    if (Reader.parse(*HttpData.get(), RecivedData))
                    {
                        std::cout << colors::bright_green << "[+] " << colors::white << "Successfully parsed JSON data.\n";
                        std::cout << colors::bright_yellow << "[!] " << colors::white << "5sim User information: \n" << RecivedData.toStyledString();
    
                        ULONG UserID(RecivedData["id"].asUInt64());
                        std::string UserEmail(RecivedData["email"].asString());
                        std::string UserVendor(RecivedData["vendor"].asString());
                        std::string UserDefaultForwardingNumber(RecivedData["default_forwarding_number"].asString());
                        LONGLONG UserBalance(RecivedData["balance"].asInt64());
                        LONG UserRating(RecivedData["rating"].asInt64());
    
                        Json::Value DefaultCountry;
                        Json::Value DefaultOperator;
                        if (Reader.parse(RecivedData["default_country"].toStyledString().c_str(), DefaultCountry))
                        {
                            std::string UserDefaultCountry = DefaultCountry["name"].asString();
                            std::string UserDefaultCountryISO = DefaultCountry["iso"].asString();
                            std::string UserDefaultCountryPrefix = DefaultCountry["prefix"].asString();
                            if (Reader.parse(RecivedData["default_operator"].toStyledString().c_str(), DefaultOperator))
                            {
                                std::string UserDeafultOperatorName = DefaultCountry["name"].asString();
                                ULONG UserFrozenBalance(RecivedData["frozen_balance"].asUInt64());
                                return { UserID, UserEmail, UserVendor, UserDefaultForwardingNumber, UserBalance, UserRating, UserDefaultCountry, UserDefaultCountryISO, UserDefaultCountryPrefix, UserDeafultOperatorName, UserFrozenBalance };
                            }
                            else
                            {
                                std::cout << colors::bright_red << "[-] " << colors::white << "Unable to parse data from \"default_operator\".\n";
                            }
                        }
                        else
                        {
                            std::cout << colors::bright_red << "[-] " << colors::white << "Unable to parse data from \"default_country\".\n";
                        }
                    }
                    else
                    {
                        std::cout << colors::bright_red << "[-] " << colors::white << "Unable to parse recived data from HTTP GET attempt.\n";
                    }
            }
            else if (HttpCode == 401)
            {
                std::cout << colors::bright_red << "[-] " << colors::white << "HTTP GET Code 401, Unauthorized. (#2)\n";
            }
            else
            {
                std::cout << colors::bright_red << "[-] " << colors::white << "HTTP GET Code wasn't 200 or 401 (acceptable values), unsuccessful HTTP GET attempt. Code: \n" << HttpCode;
            }
        }
        return { 0 };
        //Curl = nullptr;
    }
avkwfej4

avkwfej41#

我 只是 需要 一些 如何 POST 数据 的 指导
最 大 的 问题 是 API 不 接受 POST 数据 。
在 您 的 代码 中 , 什么 是 有效 的 , 什么 是 无效 的 并 不 十分 清楚 。
您 拥有 的 唯一 API 文档 是

https://5sim.net/v1/guest/products/" + Country + '/' + Operator;

中 的 每 一 个
我 试 过 这个 网址 , 它 的 工作 .
我 的 请求 标题 :

header out: GET /v1/guest/products/russia/any HTTP/2
Host: 5sim.net
accept: application/json

格式
回应 信 头 :

HTTP/2 200 
date: Fri, 18 Nov 2022 18:40:44 GMT
content-type: application/json
expires: Fri, 18 Nov 2022 18:40:43 GMT
cache-control: no-cache
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
pragma: no-cache
cf-cache-status: DYNAMIC
server: cloudflare
cf-ray: 76c2d61658a32286-MIA

格式
返回 此 JSON :

{"1688":{"Category":"activation","Qty":7693,"Price":5.8},"1day":{"Category":"hosting","Qty":0,"Price":114.3},"3d66":{"Category":"activation","Qty":7714,"Price":4},"3hours":{"Category":"hosting","Qty":0,"Price":85.8},"adidas":{"Category":"activation","Qty":7716,"Price":14.3},"airbnb":{"Category":"activation","Qty":7713,"Price":4.3},"alibaba":{"Category":"activation","Qty":7692,"Price":4.3},"aliexpress":{"Category":"activation","Qty":7053,"Price":2},"amazon":{"Category":"activation","Qty":6082,"Price":3},"aol":{"Category":"activation","Qty":7676,"Price":1.5},"apple":{"Category":"activation","Qty":7667,"Price":3},"auchan":{"Category":"activation","Qty":7713,"Price":1.5},"avito":{"Category":"activation","Qty":2977,"Price":7.2},"bigolive":{"Category":"activation","Qty":7638,"Price":2.9},"bilibili":{"Category":"activation","Qty":7715,"Price":1.5},"bitclout":{"Category":"activation","Qty":7716,"Price":3.6},"bittube":{"Category":"activation","Qty":7715,"Price":2.9},"blablacar":{"Category":"activation","Qty":1137,"Price":2.9},"blizzard":{"Category":"activation","Qty":7578,"Price":2.9},"blockchain":{"Category":"activation","Qty":7410,"Price":16},"bolt":{"Category":"activation","Qty":7603,"Price":3.6},"burgerking":{"Category":"activation","Qty":7710,"Price":2.9},"careem":{"Category":"activation","Qty":7704,"Price":2.9},"celebe":{"Category":"activation","Qty":7716,"Price":4},"citymobil":{"Category":"activation","Qty":7713,"Price":2.5},"clubhouse":{"Category":"activation","Qty":7711,"Price":5.8},"craigslist":{"Category":"activation","Qty":7716,"Price":3.6},"delivery":{"Category":"activation","Qty":7460,"Price":11},"dent":{"Category":"activation","Qty":7716,"Price":2.9},"detskijmir":{"Category":"activation","Qty":7705,"Price":0.75},"didi":{"Category":"activation","Qty":7716,"Price":3.6},"discord":{"Category":"activation","Qty":6874,"Price":4},"dixy":{"Category":"activation","Qty":7716,"Price":2.9},"dodopizza":{"Category":"activation","Qty":7705,"Price":2.9},"dostavista":{"Category":"activation","Qty":7716,"Price":1.5},"douyu":{"Category":"activation","Qty":7716,"Price":3.6},"drom":{"Category":"activation","Qty":7709,"Price":2.9},"drugvokrug":{"Category":"activation","Qty":7714,"Price":2.9},"dukascopy":{"Category":"activation","Qty":7716,"Price":2.9},"ebay":{"Category":"activation","Qty":7715,"Price":2.9},"eldorado":{"Category":"activation","Qty":7716,"Price":3.6},"electroneum":{"Category":"activation","Qty":7716,"Price":2.9},"facebook":{"Category":"activation","Qty":7512,"Price":5},"fiverr":{"Category":"activation","Qty":7675,"Price":2.9},"foodpanda":{"Category":"activation","Qty":7698,"Price":2.9},"forwarding":{"Category":"activation","Qty":0,"Price":42.9},"galaxy":{"Category":"activation","Qty":7716,"Price":3.6},"gameflip":{"Category":"activation","Qty":7716,"Price":2.9},"get":{"Category":"activation","Qty":7716,"Price":2.9},"gett":{"Category":"activation","Qty":7715,"Price":1.5},"globus":{"Category":"activation","Qty":7711,"Price":2.2},"google":{"Category":"activation","Qty":2188,"Price":5.5},"grabtaxi":{"Category":"activation","Qty":7715,"Price":2.9},"green":{"Category":"activation","Qty":7716,"Price":2.2},"grindr":{"Category":"activation","Qty":7709,"Price":2.2},"handypick":{"Category":"activation","Qty":7716,"Price":3},"hqtrivia":{"Category":"activation","Qty":7715,"Price":2.9},"imo":{"Category":"activation","Qty":7647,"Price":1.5},"instagram":{"Category":"activation","Qty":7459,"Price":3},"iost":{"Category":"activation","Qty":7716,"Price":2.9},"iplum":{"Category":"activation","Qty":7716,"Price":6},"iqiyi":{"Category":"activation","Qty":7716,"Price":2},"jd":{"Category":"activation","Qty":7695,"Price":2.9},"kakaotalk":{"Category":"activation","Qty":7636,"Price":6},"komandacard":{"Category":"activation","Qty":7715,"Price":4.3},"lbry":{"Category":"activation","Qty":7716,"Price":2.9},"lenta":{"Category":"activation","Qty":7696,"Price":2.9},"letual":{"Category":"activation","Qty":7693,"Price":3},"lianxin":{"Category":"activation","Qty":7716,"Price":2.9},"line":{"Category":"activation","Qty":7707,"Price":1.5},"linkedin":{"Category":"activation","Qty":7711,"Price":1.5},"lybrate":{"Category":"activation","Qty":7716,"Price":6},"magnit":{"Category":"activation","Qty":7422,"Price":1},"magnolia":{"Category":"activation","Qty":7714,"Price":2.9},"mailru":{"Category":"activation","Qty":5988,"Price":19.3},"makemoney":{"Category":"activation","Qty":6341,"Price":15},"mcdonalds":{"Category":"activation","Qty":7704,"Price":4.3},"meetme":{"Category":"activation","Qty":7714,"Price":2.9},"mega":{"Category":"activation","Qty":7716,"Price":2.9},"michat":{"Category":"activation","Qty":7716,"Price":2.9},"microsoft":{"Category":"activation","Qty":1929,"Price":2},"minima":{"Category":"activation","Qty":7716,"Price":4},"miratorg":{"Category":"activation","Qty":7712,"Price":2.9},"mtscashback":{"Category":"activation","Qty":4748,"Price":4.3},"mvideo":{"Category":"activation","Qty":7713,"Price":4},"mygames":{"Category":"activation","Qty":7716,"Price":11},"naver":{"Category":"activation","Qty":7683,"Price":2.9},"netflix":{"Category":"activation","Qty":7653,"Price":2.9},"nifty":{"Category":"activation","Qty":7716,"Price":14.3},"nike":{"Category":"activation","Qty":7644,"Price":7},"nimses":{"Category":"activation","Qty":7716,"Price":2.9},"nttgame":{"Category":"activation","Qty":7716,"Price":2.9},"odnoklassniki":{"Category":"activation","Qty":7643,"Price":12},"offerup":{"Category":"activation","Qty":7716,"Price":3.6},"okcupid":{"Category":"activation","Qty":7697,"Price":2.9},"okey":{"Category":"activation","Qty":7716,"Price":2.9},"olx":{"Category":"activation","Qty":6722,"Price":1.5},"openpoint":{"Category":"activation","Qty":7716,"Price":2.9},"oraclecloud":{"Category":"activation","Qty":7716,"Price":2.9},"other":{"Category":"activation","Qty":4873,"Price":4},"ozon":{"Category":"activation","Qty":7690,"Price":2},"paypal":{"Category":"activation","Qty":7690,"Price":8},"perekrestok":{"Category":"activation","Qty":7709,"Price":2.9},"pokermaster":{"Category":"activation","Qty":7716,"Price":2.9},"potato":{"Category":"activation","Qty":7713,"Price":2.9},"proton":{"Category":"activation","Qty":7710,"Price":1.5},"protp":{"Category":"activation","Qty":7716,"Price":4.3},"pubg":{"Category":"activation","Qty":7715,"Price":2.9},"pyaterochka":{"Category":"activation","Qty":7465,"Price":1},"qiwiwallet":{"Category":"activation","Qty":4773,"Price":14},"redbook":{"Category":"activation","Qty":7664,"Price":4.3},"samokat":{"Category":"activation","Qty":7438,"Price":2.9},"sbermarket":{"Category":"activation","Qty":7444,"Price":3},"seosprint":{"Category":"activation","Qty":7716,"Price":2.9},"seznam":{"Category":"activation","Qty":7713,"Price":4},"sheerid":{"Category":"activation","Qty":7716,"Price":2.9},"signal":{"Category":"activation","Qty":7667,"Price":6},"skout":{"Category":"activation","Qty":7716,"Price":2.9},"snapchat":{"Category":"activation","Qty":7222,"Price":2.9},"steam":{"Category":"activation","Qty":6783,"Price":2.9},"steemit":{"Category":"activation","Qty":7716,"Price":4.3},"sunlight":{"Category":"activation","Qty":7713,"Price":1},"swvl":{"Category":"activation","Qty":7716,"Price":3.6},"tango":{"Category":"activation","Qty":7710,"Price":2.9},"tantan":{"Category":"activation","Qty":7709,"Price":2.9},"telegram":{"Category":"activation","Qty":2730,"Price":18},"tencentqq":{"Category":"activation","Qty":7552,"Price":2.9},"teremok":{"Category":"activation","Qty":7716,"Price":1.5},"tiktok":{"Category":"activation","Qty":7384,"Price":1.5},"tinder":{"Category":"activation","Qty":7516,"Price":1.5},"totalcoin":{"Category":"activation","Qty":7716,"Price":2.9},"truecaller":{"Category":"activation","Qty":7707,"Price":2.9},"twitch":{"Category":"activation","Qty":7715,"Price":2},"twitter":{"Category":"activation","Qty":2909,"Price":1},"uber":{"Category":"activation","Qty":7649,"Price":5.8},"uploaded":{"Category":"activation","Qty":7716,"Price":2.9},"vernyi":{"Category":"activation","Qty":7716,"Price":2.9},"viber":{"Category":"activation","Qty":2820,"Price":2},"vipvending":{"Category":"activation","Qty":7716,"Price":1},"vkontakte":{"Category":"activation","Qty":3311,"Price":11},"wechat":{"Category":"activation","Qty":7698,"Price":21.5},"weibo":{"Category":"activation","Qty":7714,"Price":2.9},"weku":{"Category":"activation","Qty":7716,"Price":2.9},"whatsapp":{"Category":"activation","Qty":53,"Price":5},"whoosh":{"Category":"activation","Qty":7085,"Price":3},"wink":{"Category":"activation","Qty":7700,"Price":4},"winston":{"Category":"activation","Qty":7716,"Price":2.9},"wolt":{"Category":"activation","Qty":7716,"Price":5.8},"yahoo":{"Category":"activation","Qty":7657,"Price":2.9},"yalla":{"Category":"activation","Qty":7712,"Price":2.9},"yandex":{"Category":"activation","Qty":1004,"Price":1},"yappy":{"Category":"activation","Qty":7403,"Price":4},"yemeksepeti":{"Category":"activation","Qty":0,"Price":6},"youdo":{"Category":"activation","Qty":6559,"Price":2.9},"youla":{"Category":"activation","Qty":7708,"Price":11},"zalo":{"Category":"activation","Qty":7713,"Price":2.9},"zoho":{"Category":"activation","Qty":7716,"Price":3.6}}

格式
如果 你 对 此 没有 问题 , 那么 就 把 它 从 你 的 问题 中 删除 。 它 只 是 分散 注意 力 。
你 不仅 没有 提供 任何 文件 , 你 也 没有 说明 你 收到 的 答复 。
Regarding the "https://5sim.net/v1/user/profile/"; request.
我 想 查看 请求 标 头 和 响应 标 头 :

CURLINFO_HEADER_OUT
CURLOPT_HEADER

格式
curl 响应 错误 代码

res = curl_easy_perform(curl);

if(res != CURLE_OK)
  fprintf(stderr, "curl_easy_perform() failed: %s\n",
  curl_easy_strerror(res));

格式

    • 更新 * *

我 找到 文件 了 。
不 应 使用 CURLOPT_POSTFIELDS
这 是 一 个 GET 请求 。
删除 此 :

curl_easy_setopt(Curl,JSONHeader.toStyledString().c_str());

格式
添加 以下 内容 :

list = curl_slist_append(NULL, "Accept: application/json");
  list = curl_slist_append(list, "Authorization": "Bearer " + APIKey");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);

格式
来源 : CURLOPT_HEADEROPT explained

# # 更新 2

我 不 使用 curl_easy , 在 过去 的 35 年 里 我 没有 写 过 任何 C 代码 。 我 可能 从来 没有 写 过 任何 C + + 。 我 通常 使用 PHP 。
也许 你 可以 简化 代码 。
这 是 我 的 PHP 代码 , 它 工作 正常 。 我 确实 使用 了 很多 不 必要 的 选项 来 排除 故障 。 我 注册 了 自己 的 授权 令牌 。

$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Authorization: Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDAzNDI3MjcsImlhdCI6MTY2ODgwNjcyNywicmF5IjoiNTM5ZmZiOWY4OGMxZTc1MTZjNjhiY2VhZjRlMzVmN2UiLCJzdWIiOjEzMjkxNTR9.rcyMOxzRFMW6tMBJcrBX1kq1aOYdw_Koa5p3x3buJ-QNi7kvVIYLcMWODFD2VhqW2OlmY7A8jckBWXgaw5U1Jwl37y5E9eYXsCSfqTIobmeMk_fVw-2NriE-ZtaA14XuiUTt91JOrb8KzIczedgaJ0KSZ2nwF-HCw87dx-l23CQAp6lTIHBZ8VwFuZhRWCAwY2bagpasC73IG7MavATaivipciuf2uHQNv5ABGBGnpz-3mkRzYS74MDYqTduMSIYkpIbW782sA6I5ms0qq-pqmSG7ESHAC635foKFw_6ZKKIPOStWrgTfrzcIWr5L38poIKEg';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://5sim.net/v1/user/profile');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

格式
以下 选项 不是 必需 的 。
它们 用于 故障 排除 。
它 只 与 上述 选项 一起 工作 。

curl_setopt($ch, CURLOPT_HTTPGET,true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT,2);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_ENCODING,"");
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$response = curl_exec($ch);
echo curl_error($ch);
echo $response;
echo "\nheader out: " . curl_getinfo($ch,CURLINFO_HEADER_OUT);

格式
我 的 请求 标题 :

header out: GET /v1/user/profile HTTP/2
Host: 5sim.net
accept-encoding: deflate, gzip, br
accept: application/json
authorization: Bearer  eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDAzNDI3MjcsImlhdCI6MTY2ODgwNjcyNywicmF5IjoiNTM5ZmZiOWY4OGMxZTc1MTZjNjhiY2VhZjRlMzVmN2UiLCJzdWIiOjEzMjkxNTR9.rcyMOxzRFMW6tMBJcrBX1kq1aOYdw_Koa5p3x3buJ-QNi7kvVIYLcMWODFD2VhqW2OlmY7A8jckBWXgaw5U1Jwl37y5E9eYXsCSfqTIobmeMk_fVw-2NriE-ZtaA14XuiUTt91JOrb8KzIczedgaJ0KSZ2nwF-HCw87dx-l23CQAp6lTIHBZ8VwFuZhRWCAwY2bagpasC73IG7MavATaivipciuf2uHQNv5ABGBGnpz-3mkRzYS74MDYqTduMSIYkpIbW782sA6I5ms0qq-pqmSG7ESHAC635foKFw_6ZKKIPOStWrgTfrzcIWr5L38poIKEg';

格式
我 的 回应 :

{"id":1322384,"email":"py@example.com","balance":0,"rating":96,"default_country":{"name":"russia","iso":"ru","prefix":"+7"},"default_operator":{"name":""},"frozen_balance":0}

格式
回应 信 头 :

HTTP/2 200 
date: Fri, 18 Nov 2022 21:34:53 GMT
content-type: application/json
expires: Fri, 18 Nov 2022 21:34:52 GMT
cache-control: no-cache
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
pragma: no-cache
cf-cache-status: DYNAMIC
server: cloudflare
cf-ray: 76c3d52cd90b09d6-MIA
content-encoding: br

格式
我 不能 帮助 你 的 C + + 或 回调 。
我 会 从 非常 基本 的 代码 开始 , 然后 在 您 得到 有效 的 响应 后 添加 其他 特性 。
你 能 把 你 的 代码 简化 成 这样 吗 :

list = curl_slist_append(NULL, "Accept: application/json");
list = curl_slist_append(list, "Authorization": "Bearer " + APIKey");
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
curl_easy_setopt(handle, CURLOPT_URL, "https://5sim.net/v1/user/profile");
response = curl_easy_perform(handle);
print response;

格式

相关问题