C# HttpWebRequest request through proxy

好久不见. 提交于 2019-12-10 11:32:38

问题


I'm trying to make my program work through proxy but it doesn't want to (System.Net.WebException: The operation has timed out). Without proxy everything is fine

Here is a code:

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

at the same time this code works well

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

proxy is alive, i've tested it via IE. What should i do to fix it?


回答1:


few suggestions:

  1. do you use IP address for the proxy?
  2. do you need to log in to that proxy? proxy.Credentials = new NetworkCredential(User, Password);
  3. try less headers, start with few and if it works keep adding one by one

UPD: for the host - is it a valid URL? Did you put a valid port number? like www.contoso.com:8080




回答2:


Try adding the following into either your web.config or app.config depending on application type:

<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>

You can find more details and additional parameters such as user credentials etc here: http://msdn.microsoft.com/en-us/library/kd3cf2ex(v=vs.110).aspx



来源:https://stackoverflow.com/questions/22783889/c-sharp-httpwebrequest-request-through-proxy

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