注册
登录
 文档中心 产品介绍 开发指南 API接口 代码样例 使用帮助
使用C语言通过API提取链接获取代理IP的代码样例
站大爷 官方 2024-01-21 1322 浏览

温馨提示:

1.  API提取链接为站大爷控制台实例管理里生成,请勿直接复制样例使用

2.  代码样例为json格式,在生成API提取链接时注意选择JSON格式


#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <jansson.h>

size_t write_callback(void* contents, size_t size, size_t nmemb, char* buffer) {
	size_t realsize = size * nmemb;
	memcpy(buffer, contents, realsize);
	return realsize;
}

int main() {
	CURL* curl;
	CURLcode res;

	curl = curl_easy_init();
	if (curl) {
		char ip[100];  // 存放获取到的代理IP

		// 设置要调用的API接口URL
		curl_easy_setopt(curl, CURLOPT_URL, "http://www.***.com/ShortProxy/GetIP/?api=1234567890&akey=8a17ca305f683620&count=10&timespan=3&type=3");

		// 设置回调函数,将获取到的数据写入ip数组中
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, ip);

		// 执行API接口调用
		res = curl_easy_perform(curl);
		if (res != CURLE_OK) {
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		} else {
			printf("Response: %s\n", ip);

			// 解析返回的JSON数据
			json_error_t error;
			json_t* root = json_loads(ip, 0, &error);
			if (!root) {
				fprintf(stderr, "Failed to parse JSON: %s\n", error.text);
				return 1;
			}

			// 从JSON中获取代理IP
			json_t* ipObj = json_object_get(root, "ip");
			if (!json_is_string(ipObj)) {
				fprintf(stderr, "Invalid JSON format: 'ip' field is missing or not a string\n");
				json_decref(root);
				return 1;
			}

			const char* proxyIP = json_string_value(ipObj);
			printf("Proxy IP: %s\n", proxyIP);

			// 释放JSON对象
			json_decref(root);
		}

		// 清理CURL资源
		curl_easy_cleanup(curl);
	}

	return 0;
}


立即注册站大爷用户,免费试用全部产品
立即注册站大爷用户,免费试用全部产品