c#语言中怎么使用HTTP代理

电子说

1.2w人已加入

描述

c#语言中怎么使用HTTP代理。

以下代码主要围绕第一次接触HTTP代理IP的c#新手来写(步骤注释清晰)。

直接把下面示例代码中的HTTP代理API,替换成你后台生成的代理API链接,就可以跑起来了。

以下是一个示例代码,只是一个基础的演示,具体的代码还是要根据你业务的实际情况去写的。

示例代码中的HTTP代理IP,我使用的是华益云的HTTP代理API,注册就白嫖1万个高匿爬虫IP,有效期是一年,对于调试代码来说这个时间是非常的友好。

示例代码demo中同款HTTP代理API-点我免费领取10000个高匿IP

打开代理API,获取里面的IP,使用IP访问目标网站,其实代码中就是执行这个过程而已,然后加了几个错误判断有助于代码的稳定运行。(步骤注释清晰)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace proxyRequests
{
    class ProxyInfo
    {
        private string host;
        private int port;
        public ProxyInfo(string host, int port)
        {
            this.host = host;
            this.port = port;
        }
        public string getHost()
        {
            return host;
        }
        public int getPort()
        {
            return port;
        }


    }
    class Program
    {
        static void Main(string[] args)
        {
            // 发送给服务器的标识
            string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/532.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36";
            // 代理api(这里我推荐使用www.9vps.com华益云的HTTP代理API,注册就白嫖1万IP)
            string proxyUrl = "http://http.9vps.com/getip.asp?username=166xxxx6597&pwd=xxxxbaa59ce237dff65134984b9cxxxx&geshi=1&fenge=1&fengefu=&Contenttype=1&getnum=20&setcity=&operate=all&";
            List outPutProxy = getProxy(proxyUrl, userAgent);
            if (outPutProxy.Count == 0) {
                return;
            }
            // 目标请求网站
            string url = "https://www.qq.com/";
            outPutProxy.Add(new ProxyInfo("1", 0));
            for (int i = 0; i < 3; i++)
            {
                // 最多尝试三次
                try
                {
                    ProxyInfo px = outPutProxy[0];
                    outPutProxy.Remove(px);
                    WebProxy proxy = new WebProxy(px.getHost(), px.getPort());
                    string outHtml = requestGet(url, userAgent, proxy);
                    Console.WriteLine(outHtml);
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    if (outPutProxy.Count == 0)
                    {
                        // 如果发现没有代理了,就去获取下。
                        outPutProxy = getProxy(proxyUrl, userAgent);
                    }
                }
            }
            //Console.WriteLine(requestGet(@"https://www.baidu.com/", userAgent));
            //Console.ReadKey();
        }
        static List getProxy(string proxyUrl, string userAgent) {

            //String proxyUrl = "http://http1.9vps.com/getip.asp?username=用户名&pwd=API密码串&geshi=1&fenge=1&fengefu=&Contenttype=1&getnum=2";
            string proxyIps;
            List outPutProxy = new List();
            try
            {
                proxyIps = requestGet(proxyUrl, userAgent, null);
                Console.WriteLine(proxyIps);
                // {"code":3002,"data":[],"msg":"error!用户名或密码错误","success":false}
                if (proxyIps.Contains("{"))
                {
                    throw new Exception("[错误]" + proxyIps);
                }
                String[] splitedString = proxyIps.Split('\n');
                for (int i = 0; i < splitedString.Length; i++)
                {
                    /*
                     * 180.104.192.217:22036
                     * 150.104.192.217:21036

                    */
                    String[] ret = splitedString[i].Split(':');// 180.104.192.217:22036
                    String host = ret[0]; // 180.104.192.217
                    int port = int.Parse(ret[1]); // 22036 
                    outPutProxy.Add(new ProxyInfo(host, port));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            Console.WriteLine("总共获取了" + outPutProxy.Count + "个代理");

            return outPutProxy;
        }
        static string requestGet(string url, string userAgent, WebProxy proxy)
        {
           
            WebClient client = new WebClient();
            if (proxy != null)
            {
                // 设置代理部分
                client.Proxy = proxy;
            }
            // 设置编码解析方式为 UTF-8,防止中文乱码
            client.Encoding = Encoding.UTF8;
            client.Headers.Add("user-agent", userAgent);
            return client.DownloadString(url);
        }
    }
}
打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分