Advertisement
tolikpunkoff

SendRequest class

Jan 9th, 2020
758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.IO;
  6.  
  7. namespace RiseupHelperXP
  8. {
  9.     class SendRequest
  10.     {
  11.         public delegate void OnConnecting(object sender);                
  12.         public event OnConnecting Connecting;        
  13.        
  14.         private HttpWebRequest request = null;
  15.         private WebProxy proxy = null;        
  16.        
  17.         public string URL { get; set; }
  18.         public string OutputFile { get; set; }
  19.         public string Method { get; set; }
  20.  
  21.         public NetConnectionType ConnectionType { get; set; }
  22.         public string ProxyAddress { get; set; }
  23.         public int ProxyPort { get; set; }
  24.         public string ProxyUser { get; set; }
  25.         public string ProxyPassword { get; set; }        
  26.         public int ConnectionTimeout { get; set; }
  27.  
  28.         public string ErrorMessage { get; private set; }
  29.        
  30.         public SendRequest(string url, string outputfile)
  31.         {
  32.             URL = url;
  33.             OutputFile = outputfile;
  34.             Method = "GET";        
  35.         }
  36.        
  37.         public bool CreateRequest()
  38.         {
  39.             //устанавливаем минимальные параметры для запроса
  40.             try
  41.             {
  42.                 request = (HttpWebRequest)HttpWebRequest.Create(URL);
  43.             }
  44.             catch (Exception ex)
  45.             {
  46.                 ErrorMessage = "Request Error: " + ex.Message;                
  47.                 return false;
  48.             }
  49.  
  50.             switch (ConnectionType)
  51.             {
  52.                 case NetConnectionType.NoProxy:
  53.                     {
  54.                         proxy = null;
  55.                         HttpWebRequest.DefaultWebProxy = null;
  56.                         request.Proxy = proxy;
  57.                     }; break;
  58.  
  59.                 case NetConnectionType.SystemProxy:
  60.                     {
  61.                         HttpWebRequest.DefaultWebProxy = HttpWebRequest.GetSystemWebProxy();
  62.                         proxy = null;
  63.                     }; break;
  64.                 case NetConnectionType.ManualProxy:
  65.                     {
  66.                         proxy = new WebProxy(ProxyAddress, ProxyPort);
  67.                         if (!string.IsNullOrEmpty(ProxyUser)) //есть имя пользователя, надобно авторизоваться
  68.                         {
  69.                             CredentialCache cred = new CredentialCache();
  70.                             cred.Add(ProxyAddress, ProxyPort, "Basic",
  71.                                 new NetworkCredential(ProxyUser, ProxyPassword));
  72.  
  73.                             proxy.Credentials = cred;
  74.                         }
  75.  
  76.                         request.Proxy = proxy;
  77.                     }; break;
  78.             }
  79.  
  80.  
  81.             if (ConnectionTimeout > 0) request.Timeout = ConnectionTimeout;
  82.             request.Method = Method;
  83.  
  84.             return true;
  85.         }
  86.        
  87.         public bool Send()
  88.         {
  89.             if (Connecting != null) Connecting(this);
  90.            
  91.             //получаем ответ
  92.             HttpWebResponse resp = null;
  93.             FileStream writeStream = null;            
  94.             try
  95.             {
  96.                 resp = (HttpWebResponse)request.GetResponse();
  97.                 //не вывалились в ошибку, значит все OK
  98.  
  99.                 //заводим поток для записи выходного файла
  100.                 writeStream = new FileStream(OutputFile, FileMode.Create);
  101.                 int size = 1024; //размер буфера для обмена между потоками
  102.                 byte[] buf = new byte[size]; //буфер
  103.                 int count = 0; //для хранения фактически прочитанных байт
  104.  
  105.                 //получаем поток ответа
  106.                 Stream RespStream = resp.GetResponseStream();
  107.  
  108.                 //пишем данные в файл
  109.                 do
  110.                 {
  111.                     count = RespStream.Read(buf, 0, size); //читаем кусками == size
  112.  
  113.                     if (count > 0) //данные есть?
  114.                     {
  115.                         writeStream.Write(buf, 0, count); //пишем фактически
  116.                         //прочитанное кол-во байт
  117.                     }
  118.                 } while (count > 0);
  119.                 writeStream.Close(); //закрываем поток записи, сохраняем файл
  120.             }
  121.             catch (WebException webex)
  122.             {
  123.                 //вылетели в ошибку веба - пытаемся закрыть поток
  124.                 if (writeStream != null) writeStream.Close();
  125.  
  126.                 ErrorMessage = webex.Message;
  127.  
  128.                 if (webex.Status == WebExceptionStatus.ProtocolError)
  129.                 {
  130.                     //ошибка протокола (404, например)
  131.                     //интернет может и есть
  132.                     ErrorMessage = "Protocol Error: " + ErrorMessage;
  133.                     return false;
  134.                 }
  135.                 else //какая-то другая ошибка интернетов
  136.                 {
  137.                     ErrorMessage = "Network Error: " + ErrorMessage;
  138.                     return false;
  139.                 }
  140.             }
  141.             catch (Exception ex) //другая ошибка (напр. I/O error)
  142.             {
  143.                 //пытаемся закрыть поток
  144.                 if (writeStream != null) writeStream.Close();                
  145.                 ErrorMessage = "Other Error: " + ex.Message;
  146.                 return false;
  147.             }
  148.  
  149.             return true;
  150.         }                
  151.     }
  152. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement