0
点赞
收藏
分享

微信扫一扫

C# WPF HTTP代理工具

程序员伟杰 2022-04-03 阅读 28
c#wpf

C# WPF HTTP代理工具

Ui界面

<Window x:Class="httpProxyTools.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:httpProxyTools"
        mc:Ignorable="d"
        Title="HTTP代理" Height="687.205" Width="1059.978" ResizeMode="CanMinimize">
    <Grid Margin="0,0,-172,-53">
        <ListView x:Name="ListViewProxy" HorizontalAlignment="Left" Height="608" Margin="10,10,0,0" VerticalAlignment="Top" Width="850" SelectionChanged="ListViewProxy_SelectionChanged">
            <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                </Style>
            </ListView.ItemContainerStyle>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="序号" Width="50" DisplayMemberBinding="{Binding Number}"/>
                    <GridViewColumn Header="IP" Width="160" DisplayMemberBinding="{Binding IpAddress}"/>
                    <GridViewColumn Header="端口" Width="60" DisplayMemberBinding="{Binding Port}"/>
                    <GridViewColumn Header="地理位置" Width="260" DisplayMemberBinding="{Binding Location}"/>
                    <GridViewColumn Header="匿名度" Width="60" DisplayMemberBinding="{Binding AnonyMous}"/>
                    <GridViewColumn Header="协议" Width="60" DisplayMemberBinding="{Binding Protocols}"/>
                    <GridViewColumn Header="最后验证时间" Width="160" DisplayMemberBinding="{Binding VerifyDate}"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Button x:Name="Button_FlushProxyData" Content="刷新代理数据" Margin="914,10,204,638" Width="86" Height="29" Click="Button_FlushProxyData_Click"/>
        <Label x:Name="Label_ipCount" Content="已取到 0 /条 IP代理数据。" HorizontalAlignment="Left" Height="29" Margin="4,622,0,0" VerticalAlignment="Top" Width="274"/>
        <Label x:Name="Label_ipAndPort" Content="当前选中:" HorizontalAlignment="Left" Height="29" Margin="283,622,0,0" VerticalAlignment="Top" Width="577"/>
        <Button x:Name="Button_SettingProxy" Content="设置为IE代理" Margin="889,72,180,0" VerticalAlignment="Top" Width="86" Height="29" Click="Button_SettingProxy_Click"/>
        <Label x:Name="Label_ProxyStatus" Content="代理状态:" Foreground="BlueViolet" HorizontalAlignment="Center" Margin="924,593,180,0" VerticalAlignment="Top" Width="122"/>
        <Button x:Name="Button_CloseProxy" Content="关闭代理" HorizontalAlignment="Center" Height="29" Margin="889,559,180,0" VerticalAlignment="Top" Width="86" Click="Button_CloseProxy_Click"/>
        <Button x:Name="Button_StartProxy" Content="开启代理" HorizontalAlignment="Center" Height="29" Margin="889,520,180,0" VerticalAlignment="Top" Width="86" Click="Button_StartProxy_Click"/>
        <Label x:Name="Label_ProxyStatus_Copy" Content="当前代理信息:" Foreground="BlueViolet" HorizontalAlignment="Center" Margin="887,298,249,0" VerticalAlignment="Top" Width="90" Height="24"/>
        <Label x:Name="Label_ProxyInfo" Foreground="BlueViolet" HorizontalAlignment="Center" Margin="887,327,180,0" VerticalAlignment="Top" Width="159" Height="28"/>
        <Button x:Name="Button_AboutMe" Content="About Me" Margin="889,135,180,0" VerticalAlignment="Top" Width="86" Height="29" Click="Button_AboutMe_Click" />
    </Grid>

</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Windows;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace httpProxyTools
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            CheckProxyStatus();
            GetCurrentProxyInfo();
        }

        /// <summary>
        /// 检测代理状态
        /// </summary>
        public void CheckProxyStatus()
        {
            int ProxyStatus = Proxy_GetEnable();
            if (ProxyStatus == 0)
            {
                Label_ProxyStatus.Content = "代理状态:关闭";
                Button_CloseProxy.IsEnabled = false;
                Button_StartProxy.IsEnabled = true;
                Button_SettingProxy.IsEnabled = false;
            }
            else if (ProxyStatus == 1)
            {
                Label_ProxyStatus.Content = "代理状态:开启";
                Button_CloseProxy.IsEnabled = true;
                Button_StartProxy.IsEnabled = false;
                Button_SettingProxy.IsEnabled = true;
            }
            else if (ProxyStatus == -1)
            {
                Label_ProxyStatus.Content = "代理状态:异常";
                Button_StartProxy.IsEnabled = false;
                Button_CloseProxy.IsEnabled = false;
                Button_SettingProxy.IsEnabled = false;
            }
        }
        /// <summary>
        /// 读系统注册表项,取系统是否开启代理服务
        /// </summary>
        /// <returns>关闭返回0,开启返回1,返回-1则表示该注册项不存在</returns>
        public int Proxy_GetEnable()
        {
            int status = 0;
            RegistryKey regKey = Registry.CurrentUser;
            RegistryKey key = regKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
            status = Convert.ToInt32(key.GetValue("ProxyEnable", -1));
            key.Close();
            return status;
        }
        public void GetProxyIP()
        {
            String url = "https://www.beesproxy.com/free/page/";
            int number = 0;
            
            for (int page = 1; page < 89; page++)
            {
                // 随机延迟1-1500ms
                Random random = new Random();
                Task.Delay(random.Next(1,1500));

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url + Convert.ToString(page));
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode.ToString() != "OK")
                {
                    Dispatcher.Invoke(new Action(() => Label_ipCount.Content = "抱歉!网络导致访问服务器异常!等待任务结束"));
                }
                Stream stream = resp.GetResponseStream();
                try
                {
                    StreamReader reader = new StreamReader(stream);
                    String htmlData = reader.ReadToEnd();
                    String tbodyListData = MidStrEx_New(htmlData, "<tbody>", "</tbody>");
                    String[] DataArray = SubstringMultiple(tbodyListData, "<tr>", "/tr");
                    for (int index = 0; index < DataArray.Length; index++)
                    {
                        String[] tdData = SubstringMultiple(DataArray[index], "<td>", "</td>");
                        number++;
                        if (tdData[0] == "" && tdData[1] == "")
                        {
                            break;
                        }
                        Dispatcher.Invoke(new Action(() => ListViewProxy.Items.Add(new ListViewItem() { Number = number, IpAddress = tdData[0], Port = tdData[1], Location = tdData[2], AnonyMous = tdData[3], Protocols = tdData[4], VerifyDate = tdData[5] })));
                        Dispatcher.Invoke(new Action(() => Label_ipCount.Content = String.Format("已取到 {0} /条 IP代理数据 <正在获取>",Convert.ToString(number))));
                    }
                }
                finally
                {
                    stream.Close();
                }
            }
            Dispatcher.Invoke(new Action(() => Label_ipCount.Content = String.Format("已取到 {0} /条 IP代理数据 <完毕>",Convert.ToString(number))));
        }
        public string[] SubstringMultiple(string source, string startStr, string endStr)
        {
            Regex rg = new Regex("(?<=(" + startStr + "))[.\\s\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            MatchCollection matches = rg.Matches(source);
            List<string> resList = new List<string>();
            foreach (Match item in matches)
                resList.Add(item.Value);
            return resList.ToArray();
        }
        public string MidStrEx_New(string sourse, string startstr, string endstr)
       {
            Regex rg = new Regex("(?<=(" + startstr + "))[.\\s\\S]*?(?=(" + endstr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            return rg.Match(sourse).Value;
       }
        private async void Button_FlushProxyData_Click(object sender, RoutedEventArgs e)
        {
            Label_ipCount.Content = "准备获取";
            ListViewProxy.Items.Clear();
            await Task.Run(GetProxyIP);
        }

        private void ListViewProxy_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            ListViewItem emp = ListViewProxy.SelectedItem as ListViewItem;
            if (emp != null && emp is ListViewItem)
            {
                Label_ipAndPort.Content = String.Format("当前选中:{0}:{1} {2}",emp.IpAddress,emp.Port,emp.Location);
            }
        }
        private void Button_StartProxy_Click(object sender, RoutedEventArgs e)
        {
            RegistryKey registryKey = Registry.CurrentUser;
            RegistryKey key = registryKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings",true);
            key.SetValue("ProxyEnable", 1);
            key.Close();
            CheckProxyStatus();
        }

        private void Button_CloseProxy_Click(object sender, RoutedEventArgs e)
        {
            RegistryKey registryKey = Registry.CurrentUser;
            RegistryKey key = registryKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            key.SetValue("ProxyEnable", 0);
            key.Close();
            CheckProxyStatus();
        }
        private void Button_SettingProxy_Click(object sender, RoutedEventArgs e)
        {
            ListViewItem items = ListViewProxy.SelectedItem as ListViewItem;
            if (items != null && items is ListViewItem)
            {
                RegistryKey registryKey = Registry.CurrentUser;
                RegistryKey key = registryKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
                key.SetValue("ProxyServer", items.IpAddress + ":" + items.Port);
                key.Close();
                GetCurrentProxyInfo();
            }
            
        }
        public void GetCurrentProxyInfo()
        {
            RegistryKey registryKey = Registry.CurrentUser;
            RegistryKey key = registryKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            String ProxyInfo = key.GetValue("ProxyServer", -1).ToString();
            key.Close();
            Label_ProxyInfo.Content = ProxyInfo;
        }

        private void Button_AboutMe_Click(object sender, RoutedEventArgs e)
        {
            AboutMe aboutMeWindow = new AboutMe();
            aboutMeWindow.ShowDialog();
        }
    }
    public class ListViewItem
    { 
        public int Number { get; set; }
        public String IpAddress { get; set; }
        public String Port { get; set; }
        public String Location { get; set; }
        public String AnonyMous { get; set; }
        public String Protocols { get; set; }
        public String VerifyDate { get; set; }
    }
}

演示效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

本人是新手小萌,已知程序的多线程有些Bug,启动线程获取IP代理数据未完成时关闭程序会报异常崩溃,知识有限没能继续优化,也是在网上零零散散的找到些资料照葫芦画瓢写的,大神勿喷,发出来的目的是让像我这样的新手练手学习用。

举报

相关推荐

0 条评论