C++ API代理示例
流程:请求 API → 解析 JSON(简单解析或使用 nlohmann/json)→ 使用返回代理访问目标站。
1#include <curl/curl.h>2#include <string>3#include <iostream>4#include <nlohmann/json.hpp>56static size_t Write(void* contents, size_t size, size_t nmemb, void* userp){7((std::string*)userp)->append((char*)contents, size*nmemb);8return size*nmemb;9}1011int main(){12std::string api = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";13CURL* curl = curl_easy_init();14std::string buf;15if(!curl) return 1;16curl_easy_setopt(curl, CURLOPT_URL, api.c_str());17curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Write);18curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);19CURLcode res = curl_easy_perform(curl);20if(res != CURLE_OK){ std::cerr << "API失败: " << curl_easy_strerror(res) << std::endl; return 1; }21curl_easy_cleanup(curl);2223// 使用 nlohmann/json 解析返回的 JSON24std::string ip;25int port = 0;26try {27auto j = nlohmann::json::parse(buf);28if (j.is_array() && !j.empty()) {29ip = j.at(0).at("ip").get<std::string>();30port = j.at(0).at("port").get<int>();31} else if (j.is_object()) {32ip = j.at("ip").get<std::string>();33port = j.at("port").get<int>();34} else {35std::cerr << "解析失败: 返回 JSON 结构不符合预期" << std::endl;36return 1;37}38} catch (const std::exception& e) {39std::cerr << "解析失败: " << e.what() << std::endl;40return 1;41}4243// 使用代理访问 httpbin44std::string page;45curl = curl_easy_init();46if(!curl) return 1;47curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/ip");48std::string proxy = std::string("http://") + ip + ":" + std::to_string(port);49curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str());50curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Write);51curl_easy_setopt(curl, CURLOPT_WRITEDATA, &page);52res = curl_easy_perform(curl);53if(res != CURLE_OK){ std::cerr << "访问失败: " << curl_easy_strerror(res) << std::endl; return 1; }54curl_easy_cleanup(curl);55std::cout << page << std::endl;56return 0;57}