Skip to content

Latest commit

 

History

History
472 lines (375 loc) · 9.7 KB

File metadata and controls

472 lines (375 loc) · 9.7 KB

📡 API 使用文档

基本信息

  • 基础URL: http://localhost:8080
  • API版本: v1
  • 内容类型: application/json

API 端点

1. 首页信息

获取API基本信息和可用端点列表。

GET /

示例请求:

curl http://localhost:8080/

响应示例:

{
  "message": "Dynamic Proxy Pool API",
  "version": "1.0.0",
  "endpoints": {
    "random_proxy": "/api/v1/proxy/random?type=http&valid_only=true",
    "best_proxy": "/api/v1/proxy/best?type=socks&valid_only=true",
    "proxy_list": "/api/v1/proxies?type=http&valid_only=false&limit=10",
    "proxy_detail": "/api/v1/proxy/{id}",
    "stats": "/api/v1/stats",
    "health": "/api/v1/health"
  }
}

2. 获取随机代理

获取一个随机的可用代理。

GET /api/v1/proxy/random
GET /proxy  # 便捷路由

查询参数:

参数 类型 必填 默认值 说明
type string all 代理类型: http, socks
valid_only boolean true 是否只返回有效代理

示例请求:

# 获取随机HTTP代理
curl "http://localhost:8080/api/v1/proxy/random?type=http&valid_only=true"

# 便捷路由
curl "http://localhost:8080/proxy?type=http"

响应示例:

{
  "success": true,
  "data": {
    "id": "192.168.1.1:8080",
    "ip": "192.168.1.1",
    "port": 8080,
    "protocol": "http",
    "country": "US",
    "anonymity": "elite",
    "is_valid": true,
    "response_time": 1250,
    "score": 95.5,
    "fail_count": 0,
    "last_check_time": "2025-10-23T13:45:00Z",
    "created_at": "2025-10-23T13:00:00Z"
  }
}

3. 获取最佳代理

获取评分最高的代理。

GET /api/v1/proxy/best

查询参数:

参数 类型 必填 默认值 说明
type string all 代理类型: http, socks
valid_only boolean true 是否只返回有效代理

示例请求:

curl "http://localhost:8080/api/v1/proxy/best?type=http"

响应格式: 与 获取随机代理 相同


4. 获取代理列表

获取代理列表,支持筛选和分页。

GET /api/v1/proxies

查询参数:

参数 类型 必填 默认值 说明
type string all 代理类型: http, socks
valid_only boolean false 是否只返回有效代理
limit integer 10 返回数量限制

示例请求:

# 获取10个HTTP代理
curl "http://localhost:8080/api/v1/proxies?type=http&limit=10"

# 只获取有效代理
curl "http://localhost:8080/api/v1/proxies?valid_only=true&limit=20"

响应示例:

{
  "success": true,
  "total": 10,
  "data": [
    {
      "id": "192.168.1.1:8080",
      "ip": "192.168.1.1",
      "port": 8080,
      "protocol": "http",
      "country": "US",
      "anonymity": "elite",
      "is_valid": true,
      "response_time": 1250,
      "score": 95.5,
      "fail_count": 0,
      "last_check_time": "2025-10-23T13:45:00Z",
      "created_at": "2025-10-23T13:00:00Z"
    }
    // ... 更多代理
  ]
}

5. 获取代理详情

获取指定ID的代理详细信息。

GET /api/v1/proxy/:id

路径参数:

参数 类型 说明
id string 代理ID (格式: ip:port)

示例请求:

curl "http://localhost:8080/api/v1/proxy/192.168.1.1:8080"

响应格式: 与 获取随机代理 相同


6. 获取统计信息

获取代理池的统计信息。

GET /api/v1/stats
GET /stats  # 便捷路由

示例请求:

curl "http://localhost:8080/api/v1/stats"

# 或使用便捷路由
curl "http://localhost:8080/stats"

# 格式化输出
curl -s "http://localhost:8080/stats" | python3 -m json.tool

响应示例:

{
  "success": true,
  "data": {
    "total_proxies": 1110,
    "valid_proxies": 856,
    "invalid_proxies": 254,
    "http_proxies": 700,
    "https_proxies": 310,
    "socks_proxies": 100,
    "average_response_time": 1450,
    "last_update": "2025-10-23T13:45:00Z"
  }
}

7. 健康检查

检查服务是否正常运行。

GET /api/v1/health
GET /health  # 便捷路由

示例请求:

curl "http://localhost:8080/health"

响应示例:

{
  "status": "ok",
  "message": "Proxy pool service is running"
}

错误响应

当请求失败时,API会返回以下格式的错误信息:

{
  "success": false,
  "message": "错误描述信息"
}

常见HTTP状态码:

  • 200 OK - 请求成功
  • 404 Not Found - 资源不存在
  • 500 Internal Server Error - 服务器内部错误

使用示例

Python 示例

import requests
import json

# 基础URL
BASE_URL = "http://localhost:8080"

# 获取随机代理
def get_random_proxy():
    response = requests.get(f"{BASE_URL}/proxy", params={
        "type": "http",
        "valid_only": "true"
    })
    if response.status_code == 200:
        data = response.json()
        if data["success"]:
            proxy = data["data"]
            print(f"获取到代理: {proxy['ip']}:{proxy['port']}")
            return proxy
    return None

# 获取代理列表
def get_proxy_list(limit=10):
    response = requests.get(f"{BASE_URL}/api/v1/proxies", params={
        "valid_only": "true",
        "limit": limit
    })
    if response.status_code == 200:
        data = response.json()
        if data["success"]:
            proxies = data["data"]
            print(f"获取到 {len(proxies)} 个代理")
            return proxies
    return []

# 获取统计信息
def get_stats():
    response = requests.get(f"{BASE_URL}/stats")
    if response.status_code == 200:
        data = response.json()
        if data["success"]:
            stats = data["data"]
            print(json.dumps(stats, indent=2, ensure_ascii=False))
            return stats
    return None

# 使用代理进行请求
def use_proxy(target_url):
    proxy = get_random_proxy()
    if proxy:
        proxies = {
            "http": f"http://{proxy['ip']}:{proxy['port']}",
            "https": f"http://{proxy['ip']}:{proxy['port']}"
        }
        try:
            response = requests.get(target_url, proxies=proxies, timeout=10)
            print(f"请求成功: {response.status_code}")
            return response
        except Exception as e:
            print(f"请求失败: {e}")
    return None

if __name__ == "__main__":
    # 测试获取统计信息
    print("=== 代理池统计 ===")
    get_stats()
    
    print("\n=== 获取随机代理 ===")
    proxy = get_random_proxy()
    
    print("\n=== 获取代理列表 ===")
    proxies = get_proxy_list(5)

JavaScript/Node.js 示例

const axios = require('axios');

const BASE_URL = 'http://localhost:8080';

// 获取随机代理
async function getRandomProxy() {
  try {
    const response = await axios.get(`${BASE_URL}/proxy`, {
      params: {
        type: 'http',
        valid_only: true
      }
    });
    
    if (response.data.success) {
      const proxy = response.data.data;
      console.log(`获取到代理: ${proxy.ip}:${proxy.port}`);
      return proxy;
    }
  } catch (error) {
    console.error('获取代理失败:', error.message);
  }
  return null;
}

// 获取统计信息
async function getStats() {
  try {
    const response = await axios.get(`${BASE_URL}/stats`);
    
    if (response.data.success) {
      const stats = response.data.data;
      console.log('代理池统计:', JSON.stringify(stats, null, 2));
      return stats;
    }
  } catch (error) {
    console.error('获取统计失败:', error.message);
  }
  return null;
}

// 使用代理进行请求
async function useProxy(targetUrl) {
  const proxy = await getRandomProxy();
  
  if (proxy) {
    try {
      const response = await axios.get(targetUrl, {
        proxy: {
          host: proxy.ip,
          port: proxy.port
        },
        timeout: 10000
      });
      console.log(`请求成功: ${response.status}`);
      return response;
    } catch (error) {
      console.error('请求失败:', error.message);
    }
  }
  return null;
}

// 主函数
async function main() {
  console.log('=== 代理池统计 ===');
  await getStats();
  
  console.log('\n=== 获取随机代理 ===');
  await getRandomProxy();
}

main();

cURL 示例

#!/bin/bash

BASE_URL="http://localhost:8080"

# 获取统计信息
echo "=== 代理池统计 ==="
curl -s "$BASE_URL/stats" | python3 -m json.tool

# 获取随机HTTP代理
echo -e "\n=== 获取随机代理 ==="
curl -s "$BASE_URL/proxy?type=http&valid_only=true" | python3 -m json.tool

# 获取最佳代理
echo -e "\n=== 获取最佳代理 ==="
curl -s "$BASE_URL/api/v1/proxy/best?type=http" | python3 -m json.tool

# 获取代理列表
echo -e "\n=== 获取代理列表 ==="
curl -s "$BASE_URL/api/v1/proxies?limit=5&valid_only=true" | python3 -m json.tool

# 健康检查
echo -e "\n=== 健康检查 ==="
curl -s "$BASE_URL/health" | python3 -m json.tool

注意事项

  1. 代理有效性: 免费代理的可用性和稳定性较低,建议配合重试机制使用
  2. 速率限制: 目前没有速率限制,生产环境建议添加
  3. 代理验证: 系统会定期验证代理,无效代理会被自动清理
  4. 并发请求: 支持高并发访问,但建议合理控制请求频率

架构相关

本API基于fx依赖注入框架构建,详细的架构说明请参考:

技术支持

如遇问题,请查看:

  1. 服务日志输出
  2. Redis连接状态
  3. 配置文件 config.yaml