孤狼独啸

博客园 首页 新随笔 联系 订阅 管理

方法1:

CefSharp.CefSharpSettings.Proxy = new CefSharp.ProxyOptions("ip", "端口号", "用户名", "密码"); 

这种方法的缺点是无法动态改变代理IP。

方法2:在程序运行期间,动态修改代理IP

ChromiumWebBrowser wb = new ChromiumWebBrowser("https://www.baidu.com/");
wb.RequestHandler = new MyRequestHandler("rsel", "xanz");

public class MyRequestHandler : DefaultRequestHandler
        {
            string _proxyUserName = "", _proxyUserPwd = "";

            public MyRequestHandler() { }

            public MyRequestHandler(string proxyUser,string proxyPwd)
            {
                _proxyUserName = proxyUser;
                _proxyUserPwd = proxyPwd;
            }

            public override bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
            {
                if (isProxy == true)
                {
                    callback.Continue(_proxyUserName, _proxyUserPwd);

                    return true;
                }

                return false;
            }

            
           
        }

async private void SetProxy(ChromiumWebBrowser cwb, string address)

        {
            await Cef.UIThreadTaskFactory.StartNew(delegate

            {
                var rc = cwb.GetBrowser().GetHost().RequestContext;
                Dictionary<string, string> v = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(address))
                {


                    v["mode"] = "fixed_servers";

                    v["server"] = address;
                }
                else
                    v["mode"] = "direct";//设为direct表示取消代理
                string error;
                
                bool success = rc.SetPreference("proxy", v, out error);

            });

        }

需要设置/取消代理的时候,调用SetProxy方法即可。

 

posted on 2020-08-10 22:57  孤狼独啸  阅读(1015)  评论(0编辑  收藏  举报