如何使HttpWebRequest遵循系统代理,包括socks5如果设置?

时间:2014-05-06 12:33:56

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

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

特别是如果使用socks5代理,这是WebProxy

无法实现的

1 个答案:

答案 0 :(得分:-2)

您可以在代码

中按如下方式设置代理属性
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);