標籤:c# 代理 webbrowser 網路
如何為網路程式添加使用者代理程式,本人推薦使用UrlMkSetSessionOption函數,
不過該函數有一個弱點不可以X64編譯,X86編譯軟體才可以調用該函數
否則會一直返回!S_OK意義錯誤。第二呢 我建議大家在網上找找類似
http://www.proxy.com.ru/免費的代理的網站,代碼上的代理是在網上找的
幾日後你在使用My Code則沒有代理效果 因為Proxy 伺服器無效,所有後面
需要查閱方法的自己去找一個免費代理的伺服器位址 不要說我沒提醒。
我不建議大家在Wininet層使用InternetSetOption函數,
除非有必要 否則建議你使用我上面的辦法。
範例程式碼:
private void Form1_Load(object sender, EventArgs e) { SetUserProxy("210.152.131.254:3128", null, null); webBrowser1.Navigate("http://www.baidu.com/s?wd=ip"); }使用該方法只需要簡簡單單的幾句話就可以搞定 灰常方便。
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct INTERNET_PROXY_INFO { public int dwAccessType; public string lpszProxy; public string lpszProxyBypass; } [DllImport("urlmon.dll", SetLastError = true, CharSet = CharSet.Ansi)] public static extern int UrlMkSetSessionOption(int dwOption, ref INTERNET_PROXY_INFO pBuffer, int dwBufferLength, int dwReserved); [DllImport("urlmon.dll", SetLastError = true, CharSet = CharSet.Ansi)] public static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved); public const int S_OK = 0; public const int NULL = 0; public const int INTERNET_OPEN_TYPE_PROXY = 3; public const int INTERNET_OPTION_PROXY = 38; public const int INTERNET_OPTION_PROXY_USERNAME = 43; public const int INTERNET_OPTION_PROXY_PASSWORD = 44; // 置網路代理程式 private bool SetUserProxy(string address, string username, string password) { username = username ?? string.Empty; password = password ?? string.Empty; var sProxy = new INTERNET_PROXY_INFO() { lpszProxy = address, dwAccessType = INTERNET_OPEN_TYPE_PROXY }; UrlMkSetSessionOption(INTERNET_OPTION_PROXY_USERNAME, username, username.Length, NULL); UrlMkSetSessionOption(INTERNET_OPTION_PROXY_PASSWORD, password, password.Length, NULL); return UrlMkSetSessionOption(INTERNET_OPTION_PROXY, ref sProxy, 12, NULL) == S_OK; }上面的代碼也是比較簡單的,首先開闢一個INTERNET_PROXY_INFO的結構,佔12位元組
然後在.dwAccessType賦值INTERNET_OPEN_TYPE_PROXY開啟代理.lpszProxy賦代理
伺服器的地址 後面再設定 代理使用者名稱,代理使用者密碼 並把PIPI結構體傳入函數 測試一下
返回值是不是S_OK如果是返回真否則返回假 整體的代碼都不是好難 。
C# 為網路程式添加使用者代理程式