在C#中将代理与HttpWebRequest一起使用时出现问题 [英] problem using proxy with HttpWebRequest in C#

查看:351
本文介绍了在C#中将代理与HttpWebRequest一起使用时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码将代理与HttpWebRequest一起使用

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();
        }
    }

现在,如果我不使用代理服务器,则此功能可以正常工作.但是,如果我添加任何代理,它将返回空结果.如果我将同一个代理与WebClient一起使用,它的工作原理就像是魅力..我真的不知道到底是什么在阻止或窃听此错误. 任何想法或帮助将不胜感激!

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!

推荐答案

刚刚更改:using (webResponse = (HttpWebResponse)request.GetResponse())

webResponse = (HttpWebResponse)request.GetResponse();

nooby miskate ..

nooby miskate..

这篇关于在C#中将代理与HttpWebRequest一起使用时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆