开发者

problem using proxy with HttpWebRequest in C#

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 = webRe开发者_JS百科sponse.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!


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

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

nooby miskate..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜