C++ API代理示例

阅读模式

流程:请求 API → 解析 JSON(简单解析或使用 nlohmann/json)→ 使用返回代理访问目标站。

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