流程:调用 API → 解析 JSON → 处理错误 → 使用返回代理访问目标站。
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
class ApiProxyDemo
{
static string apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";
static string HttpGet(string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
using (var resp = (HttpWebResponse)req.GetResponse())
using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
{
if (resp.StatusCode != HttpStatusCode.OK)
throw new Exception($"API错误: {(int)resp.StatusCode}");
return sr.ReadToEnd();
}
}
static void VisitWithProxy(string ip, int port)
{
var proxy = new WebProxy($"http://{ip}:{port}");
var req = (HttpWebRequest)WebRequest.Create("https://httpbin.org/ip");
req.Proxy = proxy;
using (var resp = (HttpWebResponse)req.GetResponse())
using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
{
Console.WriteLine(sr.ReadToEnd());
}
}
static void Main()
{
var body = HttpGet(apiUrl);
var js = new JavaScriptSerializer();
dynamic arr = js.Deserialize<object>(body);
if (((object[])arr).Length == 0) throw new Exception("API 返回为空");
var first = (System.Collections.Generic.Dictionary<string, object>)((object[])arr)[0];
string ip = (string)first["ip"];
int port = Convert.ToInt32(first["port"]);
VisitWithProxy(ip, port);
}
}