GeckoWebBrowser设置代理IP访问网站

最近在做一些小demo,使用到了GeckoWebBrowser,它比winform自带的WebBrowser功能强大很多,在测试过程中使用到了代理,经过官方文档和百度检索,得出以下解决方案,记录一下,以备不时之需。

using Gecko;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        GeckoWebBrowser geckoWebBrowser = new GeckoWebBrowser() { Dock = DockStyle.Fill };
        public Form1()
        {
            InitializeComponent();
            panel1.Controls.Add(geckoWebBrowser);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string ip = GetNewProxyIp().Replace(":57114", "");
            GeckoPreferences.User["network.proxy.http"] = ip;
            GeckoPreferences.User["network.proxy.http_port"] = 57114;
            GeckoPreferences.User["network.proxy.type"] = 1;
        }

        /// <summary>
        /// 获得新的代理
        /// </summary>
        /// <returns></returns>
        public static string GetNewProxyIp()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("代理接口");
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString.Replace("\r\n", "");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            geckoWebBrowser.Navigate("http://www.baidu.com/");
        }
    }
}

最终效果:

THE END