C# API代理示例

阅读模式

流程:调用 API → 解析 JSON → 处理错误 → 使用返回代理访问目标站。

1
using System;
2
using System.IO;
3
using System.Net;
4
using System.Text;
5
using System.Web.Script.Serialization;
6
7
class ApiProxyDemo
8
{
9
static string apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";
10
11
static string HttpGet(string url)
12
{
13
var req = (HttpWebRequest)WebRequest.Create(url);
14
req.Method = "GET";
15
using (var resp = (HttpWebResponse)req.GetResponse())
16
using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
17
{
18
if (resp.StatusCode != HttpStatusCode.OK)
19
throw new Exception($"API错误: {(int)resp.StatusCode}");
20
return sr.ReadToEnd();
21
}
22
}
23
24
static void VisitWithProxy(string ip, int port)
25
{
26
var proxy = new WebProxy($"http://{ip}:{port}");
27
var req = (HttpWebRequest)WebRequest.Create("https://httpbin.org/ip");
28
req.Proxy = proxy;
29
using (var resp = (HttpWebResponse)req.GetResponse())
30
using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
31
{
32
Console.WriteLine(sr.ReadToEnd());
33
}
34
}
35
36
static void Main()
37
{
38
var body = HttpGet(apiUrl);
39
var js = new JavaScriptSerializer();
40
dynamic arr = js.Deserialize<object>(body);
41
if (((object[])arr).Length == 0) throw new Exception("API 返回为空");
42
var first = (System.Collections.Generic.Dictionary<string, object>)((object[])arr)[0];
43
string ip = (string)first["ip"];
44
int port = Convert.ToInt32(first["port"]);
45
VisitWithProxy(ip, port);
46
}
47
}