HttpWebRequest 代理IP 抓取数据解决办法

HttpWebRequest 代理IP 抓取数据
本帖最后由 wubeichuan1 于 2014-07-05 11:04:53 编辑

public static string GetWebRequest(string url, string ip, int port, string encode)
        {
            WebProxy proxyObject = new WebProxy("116.236.216.116", 8080);//代理设置
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
            Req.Proxy = proxyObject;  

            //Req.UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:10.0.2) Gecko/20100101 Firefox/10.0.2";
            HttpWebResponse Resp = null;
            try
            {
                Resp = (HttpWebResponse)Req.GetResponse();
            }
            catch
            {//无法连接服务器
                Method.WriteLog(ip + ":" + port + "  " + url, Property.LogPath + "403.txt");
                try { Resp = (HttpWebResponse)Req.GetResponse(); }
                catch { return "403"; };
                //return "403";
            }
            Encoding code = Encoding.GetEncoding(encode);
            string html = "";
            using (StreamReader str = new StreamReader(Resp.GetResponseStream(), code))
            {
                if (str != null)
                {
                    try
                    {
                        html = str.ReadToEnd();
                    }
                    catch
                    {//获取失败
                    }
                    finally
                    {
                        str.Close();
                    }
                }
            }
            System.Threading.Thread.Sleep(2000);
            return html;
        }


只要用了代理就会返回“远程服务器返回错误: (502) 错误的网关。”
但是在IE浏览器里面设置代理又可以正常访问,代码里面不加代理也可以抓取,加了代理就不行,不知道是什么原因。
webclient    webbrowser都试过了不行。

------解决方案--------------------
Req.UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:10.0.2) Gecko/20100101 Firefox/10.0.2";
------解决方案--------------------
没做过代理IP的,有个东西叫FIddlerCore。
话说为什么要代理IP?