【问题标题】:How to make HttpWebRequest follows the system proxy, including socks5 if is set?如果设置了socks5,如何让HttpWebRequest跟随系统代理?
【发布时间】:2014-05-06 12:33:55
【问题描述】:

HttpWebRequest似乎默认不使用系统代理,有没有办法让它使用Internet Explorer使用的系统代理?

特别是在使用 socks5 代理时,WebProxy 无法做到这一点。

【问题讨论】:

    标签: c# .net vb.net proxy httpwebrequest


    【解决方案1】:

    您可以在代码中设置代理属性如下

    string myProxyHostString = "192.168.1.200";
    int myProxyPort = 8080;
    
    HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
    request.Proxy = new WebProxy (MyProxyHostString, MyProxyPort);
    

    或者你可以在配置文件中进行如下配置

    <system.net>
      <defaultProxy enabled="true">
        <proxy proxyaddress="http://myproxyserver:8080" bypassonlocal="True"/>
      </defaultProxy>
    </system.net>
    

    如果您也想添加凭据,可以查看MSDN example

    // Create a new request to the mentioned URL.               
    HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
    
    // Obtain the 'Proxy' of the  Default browser.  
    IWebProxy proxy = myWebRequest.Proxy;
    // Print the Proxy Url to the console. 
    if (proxy != null)
    {
        Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
    } 
    else
    {
        Console.WriteLine("Proxy is null; no proxy will be used");
    }
    
    WebProxy myProxy=new WebProxy();
    
    Console.WriteLine("\nPlease enter the new Proxy Address that is to be set:");
    Console.WriteLine("(Example:http://myproxy.example.com:port)");
    string proxyAddress;
    
    try
    {
        proxyAddress =Console.ReadLine();
        if(proxyAddress.Length>0)
        {
            Console.WriteLine("\nPlease enter the Credentials (may not be needed)");
            Console.WriteLine("Username:");
            string username;
            username =Console.ReadLine();
            Console.WriteLine("\nPassword:");
            string password;
            password =Console.ReadLine();                   
            // Create a new Uri object.
            Uri newUri=new Uri(proxyAddress);
            // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
            myProxy.Address=newUri;
            // Create a NetworkCredential object and associate it with the  
            // Proxy property of request object.
            myProxy.Credentials=new NetworkCredential(username,password);
            myWebRequest.Proxy=myProxy;
        }
        Console.WriteLine("\nThe Address of the  new Proxy settings are {0}",myProxy.Address);
    

    【讨论】:

    • WebProxy 类不支持 SOCKS4 和 SOCKS5。它仅适用于 HTTP 代理。
    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多