【问题标题】:C# HttpWebRequest request through proxyC# HttpWebRequest 通过代理请求
【发布时间】:2014-04-01 11:00:40
【问题描述】:

我正在尝试让我的程序通过代理运行,但它不想这样做(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 对其进行了测试。我该怎么做才能解决它?

【问题讨论】:

  • 小心硬编码... 特别是 IP 地址。这就是配置文件的用途!

标签: c# httpwebrequest webproxy


【解决方案1】:

一些建议:

  1. 您是否使用 IP 地址作为代理?
  2. 您需要登录该代理服务器吗? proxy.Credentials = new NetworkCredential(User, Password);
  3. 尝试更少的标题,从少数开始,如果可行,继续一个一个添加

更新: 对于主机 - 它是有效的 URL 吗?你输入了一个有效的端口号吗? 像 www.contoso.com:8080

【讨论】:

  • 我不需要登录。对于标题建议,我会尝试
  • 它有帮助。但现在我有另一个问题。 request.Host 不适用于代理,但我需要它来发送我的 POST 请求
  • 关于标题的非常好的建议。我通过删除像“User-Agent”这样的标题解决了我的问题
【解决方案2】:

尝试将以下内容添加到您的 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

【讨论】:

  • 老兄,他想在运行时更改代理
  • 你为什么这么说?他在什么地方这么说?他的问题是如何通过代理,而不是在运行时更改。为什么要在运行时更改,因为代理不太可能在运行中途移动! :-)
  • 对不起,我的错。真的我想在运行时更改它
  • 为什么要在运行时更改它?什么情况下需要改?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多