在日常开发中经常会遇到这些需求,爬取数据,都知道现在通常用python爬取是很方便的,但是免不了还有很多伙伴在用NET来爬取,在爬取数据的时候我们知道需要使用代理服务器,如果不用代理,你的IP很有可能被封,那么微软在.NET Framework得System.Net名称空间里给我们提供了一个WebProxy类,不过这是仅仅只是一个http代理,这种代理使用起来受限太多,很不方便。如果我们需要访问更多的网络服务,socks代理是一个理想的选择。
下面是C#编写的一个使用匿名socks5代理的示例demo:
1.程序需要引入NuGet HttpToSocks5Proxy 这个是最为关键的一部
using MihaZupan; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace test { class Program { static void Main(string[] args) { //比如这个是sock5代理的IP和端口,我随便写的,你们换成自己的就行(针对的是sock5不加密的情况下写法) var socks5Hostname = "192.168.1.129"; int socks5Port = 1108; Console.WriteLine("===================================================="); Console.WriteLine("sock5代理IP:"+ socks5Hostname + ":"+ socks5Port + ""); Console.WriteLine("===================================================="); HttpToSocks5Proxy proxy = new HttpToSocks5Proxy(socks5Hostname, socks5Port); HttpClientHandler handler = new HttpClientHandler() { Proxy = proxy }; HttpClient httpClient = new HttpClient(handler, true); Task result = httpClient.GetStringAsync("https://www.xjqyc.cn"); Console.WriteLine("result:" + result.Result); Console.ReadKey(); } private static string GetTimeStamp() { TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } } }
代码运行截图
文章版权声明:除非注明,否则均为老余个人博客原创文章,转载或复制请以超链接形式并注明出处。
发表评论