c# - 每个控制台应用程序使用代理

标签 c# proxy console-application

我有一个运行一些网络爬虫控制台应用程序的虚拟机。我想知道如何为每个控制台应用程序使用不同的代理。我发现的大多数代理 C# 内容都会更改注册表,但这会更改所有控制台应用程序,而不仅仅是一个。

有没有人举例说明如何在不对所有其他控制台应用程序有效的情况下为特定控制台应用程序使用特定代理?

寻找源码解决方案

最佳答案

假设您的控制台应用程序使用一种内置方法来下载网页(WebClient、HttpWebRequest 等),它们都有一个 Proxy Property。哪个应该做你想要的。它们几乎都以相同的方式工作,所以这里是 MSDN 文档为 HttpWebRequest.Proxy 提供的示例:

// 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);
    HttpWebResponse myWebResponse=(HttpWebResponse)myWebRequest.GetResponse();

关于c# - 每个控制台应用程序使用代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8862696/

相关文章:

c# - nHibernate 析取不是预期的行为

apache - 在端口 80 上使用 apache 运行 Nodejs 服务器

c# - 是否可以在您不拥有且未创建的对象上拦截静态方法?

mysql - 在 ubuntu 16.04 中安装和使用 Mysql-proxy 时出现问题

.net-core - 如何在 .NET Core 控制台应用程序中为 HttpClient 启用日志记录?

c# - VS2015 - Visual Studio 安装程序 : No dependencies detected & won't build

c# - 谷歌 Oauth 错误 : At least one client secrets (Installed or Web) should be set

c# - 类签名中的通用约束推断

c - 如何在C中创建线程?

c++ - 当我在 C++ 控制台应用程序中打印出超过 7 个控制台输出时,为什么我的 PC 会发出蜂鸣声?