如果出现错误,请更改代理;如果已经使用代理,请更改代理
本文关键字:代理 如果 错误 | 更新日期: 2023-09-27 18:09:54
所以我不确定如何使系统喜欢为每个web请求选择其他代理&如果出现错误,请选择其他代理。我没有为它编写任何代码,但我希望有人可以为我做。
谢谢!:)
就这么做
需要一个简单的类
public class IpAndPort
{
public string IpAddress { get; set; }
public string Port { get; set; }
}
现在把代理放到列表中:
var proxies = new List<IpAndPort>
{
new IpAndPort{ IpAddress = "192.168.1.1", Port = "8012" },
new IpAndPort{ IpAddress = "192.118.1.2", Port = "8072" },
new IpAndPort{ IpAddress = "222.167.1.7", Port = "9012" },
new IpAndPort{ IpAddress = "172.145.1.4", Port = "82" }
//...
}
现在为web请求
调用以下方法var concurrentBag = new ConcurrentBag<IpAndPort>(proxies);
GetProxyWebResponse(txtUrl.Text.Trim(), concurrentBag);
private async Task<string> GetProxyWebResponse(string url, ConcurrentBag<IpAndPort> concurrentBag)
{
while (!concurrentBag.IsEmpty)
{
IpAndPort proxy;
if (!concurrentBag.TryTake(out proxy)) continue;
try
{
while (true)
{
if (!SocketConnect(proxy.IpAddress, Convert.ToInt32(proxy.Port)))
{
break;
}
var webProxy = new WebProxy(proxy.IpAddress, proxy.Port)
{
BypassProxyOnLocal = false,
Credentials = CredentialCache.DefaultCredentials
};
var request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = webProxy;
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
try
{
var response = (HttpWebResponse)request.GetResponse();
string error;
var responseFromServer = GetResponseText(response, out error);
//do work with responseFromServer
}
catch (Exception ex)
{
//ExceptionLogger.CreateFile(ex);
}
await Task.Delay(2000);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
await Task.Delay(6000);
}
return string.Empty;
}
帮助方法
public static bool SocketConnect(string host, int port)
{
var is_success = false;
try
{
var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
Thread.Sleep(500);
var hip = IPAddress.Parse(host);
var ipep = new IPEndPoint(hip, port);
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (SocketException)
{
is_success = false;
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
private static string GetResponseText(HttpWebResponse response, out string error)
{
error = string.Empty;
if (response == null)
{
error = "Listed proxy servers did not responding.";
return null;
}
var responseFromServer = string.Empty;
var responceStream = response.GetResponseStream();
if (responceStream != null)
{
using (var reader = new StreamReader(responceStream))
{
responseFromServer = reader.ReadToEnd();
}
}
return responseFromServer;
}