C#使用HTTP代理代码示例

作者: 小石头IP客服 | 来源:发表于2024-03-13 10:37 被阅读0次

    本文档为获取到代理IP后使用代理的代码样例,供开发者参考。

    代码样例直接运行无法得到正确的结果,因为代码中的代理地址/端口和应用账号密码等信息都是虚构的,您替换成自己真实的就可以正常运行了。

    如何获取代理地址/端口和设置代理授权?

    使用前提:

    1、 已经获取代理地址 ,去获取:www.xiaoshitouip.com

    2、 已经设置代理授权(用户名/密码或者IP白名单)。

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ProxySample {
        internal class Program {
            public static async Task Run() {
            // 从 https://www.xiaoshitouip.com/ 领取后,替换下面的ip和端口
                var proxy = new WebProxy("代理IP", 代理端口); //这里替换为你的代理地址和端口
    
            // 替换为自己的用户名
            // 到管理后台:https://admin.xiaoshitouip.com/proxy/proxy-auth 授权管理页面添加账号密码或者ip白名单
            // 设置了ip白名单就不需要设置账号密码了
                //这里替换成你的验证用户名和密码
                //proxy.Credentials = new NetworkCredential(userName: "账号", password: "密码"); 
    
                //HttpWebRequest用法
                var req = HttpWebRequest.Create("https://baidu.com");
                req.Proxy = proxy;
                req.Method = "GET";
                var response = req.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader sr = null;
                sr = new StreamReader(stream, Encoding.Default);
                var html = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                Console.WriteLine(html);
    
                //HttpClient用法
                var httpClientHandler = new HttpClientHandler {
                    Proxy = proxy,
                };
    
                HttpClient client = new HttpClient(httpClientHandler);
                var ret = await client.GetStringAsync("https://baidu.com");
                Console.WriteLine(ret);
            }
    
            public static void Main(string[] args) {
                Task.Run(async () => { await Program.Run(); }).Wait();
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:C#使用HTTP代理代码示例

        本文链接:https://www.haomeiwen.com/subject/zcobzdtx.html