C# API代理示例
流程:调用 API → 解析 JSON → 处理错误 → 使用返回代理访问目标站。
1using System;2using System.IO;3using System.Net;4using System.Text;5using System.Web.Script.Serialization;67class ApiProxyDemo8{9static string apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";1011static string HttpGet(string url)12{13var req = (HttpWebRequest)WebRequest.Create(url);14req.Method = "GET";15using (var resp = (HttpWebResponse)req.GetResponse())16using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))17{18if (resp.StatusCode != HttpStatusCode.OK)19throw new Exception($"API错误: {(int)resp.StatusCode}");20return sr.ReadToEnd();21}22}2324static void VisitWithProxy(string ip, int port)25{26var proxy = new WebProxy($"http://{ip}:{port}");27var req = (HttpWebRequest)WebRequest.Create("https://httpbin.org/ip");28req.Proxy = proxy;29using (var resp = (HttpWebResponse)req.GetResponse())30using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))31{32Console.WriteLine(sr.ReadToEnd());33}34}3536static void Main()37{38var body = HttpGet(apiUrl);39var js = new JavaScriptSerializer();40dynamic arr = js.Deserialize<object>(body);41if (((object[])arr).Length == 0) throw new Exception("API 返回为空");42var first = (System.Collections.Generic.Dictionary<string, object>)((object[])arr)[0];43string ip = (string)first["ip"];44int port = Convert.ToInt32(first["port"]);45VisitWithProxy(ip, port);46}47}