在使用HttpWebRequest获取目标页面的源码时,由于需要采用代理,于是就写了浏览器使用的代理 /// <summary> /// 获取页面源码 /// </summary> /// <param name="url">页面地址</param> /// <param name="server">代理服务器地址</param> /// <param name="port">代理服务器端口</param> /// <param name="username">代理服务器登录用户名</param> /// <param name="password">代理服务器登录密码</param> /// <returns></returns> public static string GetWebSource(string url, string server, int port, string username, string password) { try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Timeout = 1000 * 10; req.Method = "GET"; #region 设置Http代理 if (string.IsNullOrEmpty(server) == false) { WebProxy proxy = new WebProxy(server, port); if (string.IsNullOrEmpty(username) == false) { proxy.Credentials = new NetworkCredential(username, password); } req.Proxy = proxy; } #endregion using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) { string charSet = res.CharacterSet; if (string.IsNullOrEmpty(charSet)) { charSet = "utf-8"; } using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding(charSet))) { string webSource = sr.ReadToEnd(); return webSource; } } } catch (Exception ex) { return ex.Message; } } 调用代码如下: this.richTextBox1.Text = WebDataManager.GetWebSource("http://www.mitbbs.com/pc/pcmain.php", "127.0.0.1", 9150, null, null); 异常如下 |
|
#1 |
这问题真有那么难吗?我对这块实在是”知之甚少“,还望各位前辈相助!
|
#250分 |
可以参考
http://wenda.io/questions/293920/use-webclient-with-socks-proxy.html WebRequest/WebResponse不支持 或者下载一个ProxySocket代码 |
#3 |
@net_lover,谢谢,奋斗到今天凌晨2:00,已改用ProxySocket,重新封装了发送Http请求的代码,已实现所需功能
|
#4 |
但是代码功能还不完善,暂时就不分享出来了,等完善之后,我将在此处给出
|
#5 |
楼主在吗,请把你的代码帖一下可以吗
|