actually the question in the title of the topic. There is a code that sends a request using a proxy and there are exceptions in case of an error, and there is also a text file that contains replacement proxies, in case the used proxy is not working. The question is how do I download a new proxy and automatically send a request again, in case the current one is not working? Here is the code:

class Program { static void Main(string[] args) { try { var proxyClient = HttpProxyClient.Parse("183.207.228.7:8000"); var request = new HttpRequest(); request.UserAgent = HttpHelper.ChromeUserAgent(); request.Proxy = proxyClient; // Отправляем запрос. HttpResponse response = request.Get("http://2ip.ru/"); // Принимаем тело сообщения в виде строки. string content = response.ToString(); Console.WriteLine(content); File.WriteAllText("asd.txt", content); Console.Read(); } catch (HttpException ex) { Console.WriteLine("Произошла ошибка при работе с HTTP-сервером: {0}", ex.Message); switch (ex.Status) { case HttpExceptionStatus.Other: Console.WriteLine("Неизвестная ошибка");Console.Read(); break; case HttpExceptionStatus.ProtocolError: Console.WriteLine("Код состояния: {0}", (int)ex.HttpStatusCode);Console.Read(); break; case HttpExceptionStatus.ConnectFailure: Console.WriteLine("Не удалось соединиться с HTTP-сервером.");Console.Read(); break; case HttpExceptionStatus.SendFailure: Console.WriteLine("Не удалось отправить запрос HTTP-серверу.");Console.Read(); break; case HttpExceptionStatus.ReceiveFailure: Console.WriteLine("Не удалось загрузить ответ от HTTP-сервера.");Console.Read(); break; } } } } 

I use xNet library.

  • What does “upload a new proxy” mean? And what is a "non-working proxy"? - VladD
  • var proxyClient = HttpProxyClient.Parse ("183.207.228.7:8000"); - here is the line that is responsible for asking me to send the request. if the proxy that is inserted here is not working, how can I automatically take a new proxy from the file and insert it here, and automatically send a new request until I receive the final response from the site? - inkorpus
  • non-working proxy - a proxy through which it will be impossible to connect - inkorpus

1 answer 1

See it.

First, download the proxy list:

 var proxies = File.ReadLines("path/to/proxy.txt").ToList(); var goodProxyIndex = 0; // оформьте это в класс 

Now the procedure to attempt to read with a proxy (may throw an exception):

 string GetContent(string proxy, string address) { var proxyClient = HttpProxyClient.Parse(proxy); var request = new HttpRequest(); request.UserAgent = HttpHelper.ChromeUserAgent(); request.Proxy = proxyClient; // Отправляем запрос. HttpResponse response = request.Get(address); // Принимаем тело сообщения в виде строки. return response.ToString(); } 

Well and binding:

 var numProxies = proxies.Count; for (var try = 0; try < numProxies; try++) { try { return GetContent(proxies[goodProxyIndex], address); } catch (тут исключения, которые значат, что нельзя подключиться) { // прокси плохой, пробуем следующий goodProxyIndex = (goodProxyIndex + 1) % numProxies; } } // если мы тут, хороших прокси не осталось throw new NoGoodProxyException(); 

You may want to keep statistics on proxy and delete those that do not work more, say, 5 times.


Update: That's it all together

 class ProxyDowloader { List<string> proxies; int goodProxyIndex = 0; public ProxyDownloader(string pathToProxy) { proxies = File.ReadLines("path/to/proxy.txt").ToList(); } private string GetContent(string proxy, string address) { var proxyClient = HttpProxyClient.Parse(proxy); var request = new HttpRequest(); request.UserAgent = HttpHelper.ChromeUserAgent(); request.Proxy = proxyClient; // Отправляем запрос. HttpResponse response = request.Get(address); // Принимаем тело сообщения в виде строки. return response.ToString(); } public string GetProxiedContent(string address) { var numProxies = proxies.Count; for (var try = 0; try < numProxies; try++) { try { return GetContent(proxies[goodProxyIndex], address); } catch (тут исключения, которые значат, что нельзя подключиться) { // прокси плохой, пробуем следующий goodProxyIndex = (goodProxyIndex + 1) % numProxies; } } // если мы тут, хороших прокси не осталось throw new NoGoodProxyException(); } } 

We use:

 var dl = new ProxyDowloader("path/to/proxylist"); try { var content = dl.GetProxiedContent("http://2ip.ru"); File.WriteAllText("some.file.txt", content); } catch { // что-то сказать пользователю } Console.Read(); // если вам уж так хочется 
  • @inkorpus: It should be easy. If there is no going out, ask again. - VladD pm
  • cs623622.vk.me/v623622064/27770/2z3gdr5CW48.jpg - well, this is how I rewrote your code, only the 1st proxy is taken from the file. if it is correct, then the reading occurs as it should, if not the correct one, then the next proxy does not go. what needs to be fixed? - inkorpus
  • @inkorpus: Why did you add Console.Read to internal functions? You removed return GetContent(proxies[goodProxyIndex], address); , and it was important, as it was out of the cycle. Make a separate function from the binding code, do not be lazy :-) - VladD
  • How to make a separate function out of this?) I won't understand this - inkorpus
  • @inkorpus: Now add to the answer - VladD