problem using proxy with HttpWebRequest in C#

只谈情不闲聊 提交于 2020-01-06 08:57:08

问题


I'm using this code to use proxy with HttpWebRequest

    public string GetBoardPageResponse(string url, string proxy = "")
    {
        ServicePointManager.Expect100Continue = false;
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        HttpWebResponse response = null;

        WebProxy myProxy = new WebProxy(proxy);
        request.Proxy = myProxy;

        request.Timeout = 20000;
        request.ReadWriteTimeout = 20000;

        request.Accept = "*/*";
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729)";
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        // SEND POST         
        Stream os = null;
        StreamReader sr = null;
        try
        {
            //post data
            byte[] bytes = Encoding.ASCII.GetBytes(param);
            if (param.Length > 0)
            {
                request.ContentLength = bytes.Length;   //Count bytes to send
                os = request.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         //Send it
            } 

            // Get the response
            HttpWebResponse webResponse; 
            using (webResponse = (HttpWebResponse)request.GetResponse())

            if (webResponse == null)
                return "";

            sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding(webResponse.CharacterSet));
            string encoding = webResponse.CharacterSet;

            string data = sr.ReadToEnd().Trim();


            return data;
        }
        catch (Exception ex)
        {
            return "";
        }
        finally
        {
            if (sr != null)
                sr.Close();
            if (response != null)
                response.Close();
            if (os != null)
                os.Close();
        }
    }

now this function works fine if I don't use proxy server. but If I add any proxy it will return null result. if I use same proxy with WebClient it works like charm.. I really have no idea what's really blocking or bugging this.. any ideas or help will be appreciated!


回答1:


just changed: using (webResponse = (HttpWebResponse)request.GetResponse())

to webResponse = (HttpWebResponse)request.GetResponse();

nooby miskate..



来源:https://stackoverflow.com/questions/6161608/problem-using-proxy-with-httpwebrequest-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!