我在HttpwebRequest中添加Host时代理不工作c#

时间:2014-05-01 13:15:11

标签: c# httpwebrequest web-scraping

我正在尝试使用HttpWebRequest发布信息登录网站。它工作得很好。但是,当我使用代理登录它不会工作。连接超时,如果我删除部分:

request.Host="abc.com&#34 ;;

使用代理可以很好地工作,但执行上述操作将禁止我登录,因为该站点需要该信息。我怎么能得到任何建议?

CODE"

                HttpWebRequest httpWReq =
               (HttpWebRequest)WebRequest.Create(url);

                ASCIIEncoding encoding = new ASCIIEncoding();
                string postData = post;
                byte[] data = encoding.GetBytes(postData);

                string proxy = "58.20.127.26:3128";
               /////byte[] data = GetBytes(postData);
                WebProxy myProxy = new WebProxy(proxy);
                httpWReq.Proxy = myProxy;

                httpWReq.Method = "POST";
                httpWReq.Accept = "text/html, application/xhtml+xml, */*";
                httpWReq.Referer = refferr;
                httpWReq.CookieContainer = yumCookies;
                httpWReq.ContentType = "application/x-www-form-urlencoded";
                httpWReq.UserAgent = "xxxxxxxxxxx";
                httpWReq.Host = "xxx.com";
                httpWReq.Headers.Add("Accept-Language: en-US");
                httpWReq.ContentLength = data.Length;
                httpWReq.KeepAlive = true;
                httpWReq.Headers.Add("Pragma: no-cache");
                httpWReq.AllowAutoRedirect = true;
                httpWReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                using (Stream stream = httpWReq.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream responseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(responseStream);
                    responseString = myStreamReader.ReadToEnd();

                    if (response.Cookies.Count > 0)
                    {
                        foreach (Cookie ck in response.Cookies)
                        {
                            yumCookies.Add(ck);

                        }
                    }
                }
                response.Close();

                response = null;
                response = null;

1 个答案:

答案 0 :(得分:0)

您可以分享更多细节,例如您如何创建请求,设置代理等?通常,您不必像这样明确地设置主机。

这是我所拥有的代码的副本,它与代理完全一致:

                    var req = WebRequest.Create("http://google.com") as HttpWebRequest;
                    req.Proxy = new WebProxy("proxy-ip", 8080); //proxy ip/port
                    req.ContentType = "text/html";
                    req.Method = "GET";