如何使HttpWebRequest遵循系统代理,包括socks5如果设置
本文关键字:包括 socks5 如果 设置 代理 系统 何使 HttpWebRequest | 更新日期: 2023-09-27 18:01:50
HttpWebRequest
似乎默认不遵循系统代理,是否有办法使其使用Internet Explorer使用的系统代理?
特别是如果使用socks5代理,这在WebProxy
是不可能的。
您可以在以下代码
中设置代理属性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的例子
// 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);