C#HttpWebRequest请求通过代理

时间:2014-04-01 11:00:41

标签: c# httpwebrequest webproxy

我试图让我的程序通过代理工作,但它并不想要(System.Net.WebException:操作已经超时)。 没有代理一切都很好

这是一段代码:

        string proxy = "154.46.33.157";
        int port = 8080;
        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = "email=" + email + "&pass=" + pass;
        byte[] data = encoding.GetBytes(postData);
        WebProxy myproxy = new WebProxy(proxy, port);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("SITE");
        WebHeaderCollection myWebHeaderCollection = request.Headers;
        request.CookieContainer = sCookie;
        request.Method = "POST";
        request.Proxy = myproxy;
        request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
        request.ContentLength = data.Length;
        request.Host = "HOST";
        request.UserAgent = "[UA]";
        request.Referer = "reffer";
        request.KeepAlive = false;
        request.Timeout = 20000;

        Stream stream = request.GetRequestStream(); // TIMEOUT HERE
        stream.Write(data, 0, data.Length);
        stream.Close();
        request.GetResponse()
            .Close();

同时此代码运行良好

        string proxy = "154.46.33.157";
        int port = 8080;
        WebProxy myproxy = new WebProxy(proxy, port);
        WebRequest req = WebRequest.Create("SITE");
        req.Timeout = 5000;
        req.GetResponse();

代理还活着,我通过IE测试了它。我该怎么做才能解决它?

2 个答案:

答案 0 :(得分:1)

根据应用类型,尝试将以下内容添加到web.configapp.config中:

<configuration>

    <system.net>
        <defaultProxy>
            <proxy
                usesystemdefaults="true"
                proxyaddress="http://154.46.33.157:8080"
                bypassonlocal="true" />
              <bypasslist
                <add address="[a-z]+\.contoso\.com" />
            </bypasslist>
        </defaultProxy>
    </system.net>          

     <!-- The rest of your config here ... -->

</configuration>

您可以在此处找到更多详细信息和其他参数,例如用户凭据等:http://msdn.microsoft.com/en-us/library/kd3cf2ex(v=vs.110).aspx

答案 1 :(得分:1)

几点建议:

  1. 您是否使用IP地址代理?
  2. 您需要登录该代理吗? proxy.Credentials = new NetworkCredential(User,Password);
  3. 尝试少量标题,从少量开始,如果有效则继续逐一添加
  4. UPD: 对于主机 - 它是一个有效的URL?你有没有放一个有效的端口号? 比如www.contoso.com:8080