Professional Applications Programmers/Consultants برمجة واستشارات تطبيقات الإنترنت
Skip Navigation LinksHome » Code Library » Http

Public general use code classes and xml files that we've compiled and used over the years:

Contains functions that relate to posting and receiving data from remote Internet/Intranet pages

   1:  using System;
   2:  using System.Net;
   3:  using System.Text;
   4:  using System.IO;
   5:  using System.Net.Http;
   6:  using System.Net.Http.Headers;
   7:  using System.Threading.Tasks;
   8:   
   9:  namespace Ia.Cl.Model
  10:  {
  11:      ////////////////////////////////////////////////////////////////////////////
  12:   
  13:      /// <summary publish="true">
  14:      /// Contains functions that relate to posting and receiving data from remote Internet/Intranet pages
  15:      /// </summary>
  16:      /// <remarks> 
  17:      /// Copyright � 2001-2016 Jasem Y. Al-Shamlan (info@ia.com.kw), Internet Applications - Kuwait. All Rights Reserved.
  18:      ///
  19:      /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
  20:      /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  21:      ///
  22:      /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  23:      /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  24:      /// 
  25:      /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
  26:      /// 
  27:      /// Copyright notice: This notice may not be removed or altered from any source distribution.
  28:      /// </remarks> 
  29:      public class Http
  30:      {
  31:          ////////////////////////////////////////////////////////////////////////////
  32:   
  33:          /// <summary>
  34:          ///
  35:          /// </summary>
  36:          private static bool range = false;
  37:   
  38:          ////////////////////////////////////////////////////////////////////////////
  39:   
  40:          /// <summary>
  41:          ///
  42:          /// </summary>
  43:          public Http() { }
  44:   
  45:          // Note that "https://" and "http://" are different. wrong protocol could produce a "(403) Forbidden" response.
  46:   
  47:          // Include custom cookies, start and end points, and posting of data to remove server.
  48:   
  49:          ////////////////////////////////////////////////////////////////////////////
  50:   
  51:          /// <summary>
  52:          /// 
  53:          /// </summary>
  54:          public static async Task<T> RunAsync<T>(string baseAddress, string serviceUrl)
  55:          {
  56:              T t;
  57:   
  58:              t = default(T);
  59:   
  60:              using (var client = new HttpClient())
  61:              {
  62:                  client.BaseAddress = new Uri(baseAddress);
  63:                  client.DefaultRequestHeaders.Accept.Clear();
  64:                  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  65:   
  66:                  HttpResponseMessage response = await client.GetAsync(serviceUrl);
  67:                  if (response.IsSuccessStatusCode)
  68:                  {
  69:                      t = await response.Content.ReadAsAsync<T>();
  70:                  }
  71:              }
  72:   
  73:              return t;
  74:          }
  75:   
  76:          ////////////////////////////////////////////////////////////////////////////
  77:   
  78:          /// <summary>
  79:          /// 
  80:          /// </summary>
  81:          public static async Task<T> RunSync<T>(string baseAddress, string serviceUrl)
  82:          {
  83:              T t;
  84:   
  85:              t = default(T);
  86:   
  87:              using (var client = new HttpClient())
  88:              {
  89:                  client.BaseAddress = new Uri(baseAddress);
  90:                  client.DefaultRequestHeaders.Accept.Clear();
  91:                  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  92:   
  93:                  HttpResponseMessage response = client.GetAsync(serviceUrl).Result;
  94:                  if (response.IsSuccessStatusCode)
  95:                  {
  96:                      t = response.Content.ReadAsAsync<T>().Result;
  97:                  }
  98:                  else
  99:                  {
 100:   
 101:                  }
 102:              }
 103:   
 104:              return t;
 105:          }
 106:   
 107:          ////////////////////////////////////////////////////////////////////////////
 108:   
 109:          /// <summary>
 110:          ///
 111:          /// </summary>
 112:          public static string Request(string url)
 113:          {
 114:              range = false;
 115:   
 116:              return ProcessRequest(url, 0, false, null, null);
 117:          }
 118:   
 119:          ////////////////////////////////////////////////////////////////////////////
 120:   
 121:          /// <summary>
 122:          ///
 123:          /// </summary>
 124:          public static string Request(string url, int start)
 125:          {
 126:              range = true;
 127:   
 128:              return ProcessRequest(url, start, false, null, null);
 129:          }
 130:   
 131:          ////////////////////////////////////////////////////////////////////////////
 132:   
 133:          /// <summary>
 134:          ///
 135:          /// </summary>
 136:          public static string Request2(string url)
 137:          {
 138:              range = true;
 139:   
 140:              return ProcessRequest2(url, false);
 141:          }
 142:   
 143:          ////////////////////////////////////////////////////////////////////////////
 144:   
 145:          /// <summary>
 146:          ///
 147:          /// </summary>
 148:          public static string Request_Utf8(string url, int start)
 149:          {
 150:              range = true;
 151:   
 152:              return ProcessRequest(url, start, true, null, null);
 153:          }
 154:   
 155:          ////////////////////////////////////////////////////////////////////////////
 156:   
 157:          /// <summary>
 158:          ///
 159:          /// </summary>
 160:          public static string Request(string url, int start, System.Net.Cookie c)
 161:          {
 162:              range = true;
 163:   
 164:              return ProcessRequest(url, start, false, c, null);
 165:          }
 166:   
 167:          ////////////////////////////////////////////////////////////////////////////
 168:   
 169:          /// <summary>
 170:          ///
 171:          /// </summary>
 172:          public static string Request(string url, int start, System.Net.Cookie c1, System.Net.Cookie c2)
 173:          {
 174:              range = true;
 175:   
 176:              return ProcessRequest(url, start, false, c1, c2);
 177:          }
 178:   
 179:          ////////////////////////////////////////////////////////////////////////////
 180:   
 181:          /// <summary>
 182:          ///
 183:          /// </summary>
 184:          public static string Post(string URI, string Parameters)
 185:          {
 186:              // for a "Request format is unrecognized" problem see: http://support.microsoft.com/default.aspx?scid=kb;en-us;819267
 187:   
 188:              System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
 189:              //req.Proxy = new System.Net.WebProxy(ProxyString, true);
 190:   
 191:              req.ContentType = "application/x-www-form-urlencoded";
 192:              req.Method = "POST";
 193:              //req.Timeout = 3000;
 194:   
 195:              byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
 196:              req.ContentLength = bytes.Length;
 197:   
 198:              using (System.IO.Stream os = req.GetRequestStream())
 199:              {
 200:                  os.Write(bytes, 0, bytes.Length);
 201:                  //os.Close();
 202:              }
 203:   
 204:              System.Net.WebResponse resp = null;
 205:   
 206:              try
 207:              {
 208:                  resp = req.GetResponse();
 209:   
 210:                  if (resp == null) return null;
 211:   
 212:                  System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(1256));
 213:                  return sr.ReadToEnd().Trim();
 214:              }
 215:              catch (WebException ex)
 216:              {
 217:                  string str = ex.Message;
 218:              }
 219:   
 220:              return null;
 221:          }
 222:   
 223:          ////////////////////////////////////////////////////////////////////////////
 224:   
 225:          /// <summary>
 226:          ///
 227:          /// </summary>
 228:          public static string Post(string URI, string Parameters, int code_page)
 229:          {
 230:              // for a "Request format is unrecognized" problem see: http://support.microsoft.com/default.aspx?scid=kb;en-us;819267
 231:   
 232:              // Sometimes you need to POST in Windows 1256 code page for the process to run
 233:   
 234:              System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
 235:              //req.Proxy = new System.Net.WebProxy(ProxyString, true);
 236:   
 237:              req.ContentType = "application/x-www-form-urlencoded";
 238:              req.Method = "POST";
 239:              //req.Timeout = 3000;
 240:   
 241:              byte[] bytes = System.Text.Encoding.GetEncoding(code_page).GetBytes(Parameters);
 242:              req.ContentLength = bytes.Length;
 243:   
 244:              using (System.IO.Stream os = req.GetRequestStream())
 245:              {
 246:                  os.Write(bytes, 0, bytes.Length);
 247:                  //os.Close();
 248:              }
 249:   
 250:              System.Net.WebResponse resp = null;
 251:   
 252:              try
 253:              {
 254:                  resp = req.GetResponse();
 255:   
 256:                  if (resp == null) return null;
 257:   
 258:                  System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(code_page));
 259:                  return sr.ReadToEnd().Trim();
 260:              }
 261:              catch (WebException ex)
 262:              {
 263:                  string str = ex.Message;
 264:              }
 265:   
 266:              return null;
 267:          }
 268:   
 269:          ////////////////////////////////////////////////////////////////////////////
 270:   
 271:          /// <summary>
 272:          ///
 273:          /// </summary>
 274:          private static string ProcessRequest(string url, int start, bool utf8, System.Net.Cookie c1, System.Net.Cookie c2)
 275:          {
 276:              string text = "";
 277:   
 278:              try
 279:              {
 280:                  Uri ourUri = new Uri(url);
 281:                  // Creates an HttpWebRequest for the specified URL. 
 282:                  HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
 283:   
 284:                  // this code below is very important. It sends a request with a specific cookie in the collection
 285:                  // to demonstrate to the remote server that we have his cookie and we should skip his advertisement.
 286:                  if (c1 != null || c2 != null)
 287:                  {
 288:                      myHttpWebRequest.CookieContainer = new CookieContainer();
 289:                      if (c1 != null) myHttpWebRequest.CookieContainer.Add(c1);
 290:                      if (c2 != null) myHttpWebRequest.CookieContainer.Add(c2);
 291:                  }
 292:   
 293:                  myHttpWebRequest.Method = "POST";
 294:                  //myHttpWebRequest.Timeout = 5000; // 5 sec
 295:                  //myHttpWebRequest.MaximumResponseHeadersLength = 100; // *1024 (Kilobytes)
 296:   
 297:                  // set the range of data to be returned if the start and end positions are given
 298:                  if (range) myHttpWebRequest.AddRange(start);
 299:   
 300:                  myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
 301:                  myHttpWebRequest.ContentLength = 0;
 302:   
 303:                  HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
 304:   
 305:                  if (myHttpWebRequest.HaveResponse)
 306:                  {
 307:                      Stream receiveStream = myHttpWebResponse.GetResponseStream();
 308:                      Encoding encode;
 309:   
 310:                      if (utf8) encode = System.Text.Encoding.GetEncoding("utf-8");
 311:                      else encode = System.Text.Encoding.GetEncoding(1252); // 1252 best for western char
 312:   
 313:                      // Pipes the stream to a higher level stream reader with the required encoding format. 
 314:                      using (StreamReader readStream = new StreamReader(receiveStream, encode))
 315:                      {
 316:                          text = readStream.ReadToEnd().Trim();  // ONE
 317:   
 318:                          /*
 319:                          // TWO
 320:                          Char[] read = new Char[256];
 321:                          // Reads 256 characters at a time.    
 322:                          int count = readStream.Read( read, 0, 256 );
 323:  
 324:                          while (count > 0) 
 325:                          {
 326:                            // Dumps the 256 characters on a string and displays the string to the console.
 327:                            String str = new String(read, 0, count);
 328:                            text += str;
 329:                            count = readStream.Read(read, 0, 256);
 330:                          }
 331:                          */
 332:   
 333:                          // Releases the resources of the response.
 334:                          //myHttpWebResponse.Close();
 335:                      }
 336:                  }
 337:                  else
 338:                  {
 339:                      text = "\nResponse not received from server";
 340:                  }
 341:              }
 342:              catch (WebException e)
 343:              {
 344:                  HttpWebResponse response = (HttpWebResponse)e.Response;
 345:                  if (response != null)
 346:                  {
 347:                      if (response.StatusCode == HttpStatusCode.Unauthorized)
 348:                      {
 349:                          string challenge = null;
 350:                          challenge = response.GetResponseHeader("WWW-Authenticate");
 351:                          if (challenge != null) text = "\nThe following challenge was raised by the server: " + challenge;
 352:                      }
 353:                      else text = "\nThe following WebException was raised : " + e.Message;
 354:                  }
 355:                  else text = "\nResponse Received from server was null";
 356:              }
 357:              catch (Exception e)
 358:              {
 359:                  text = "\nThe following Exception was raised : " + e.Message;
 360:              }
 361:   
 362:              return text;
 363:          }
 364:   
 365:          ////////////////////////////////////////////////////////////////////////////
 366:   
 367:          /// <summary>
 368:          ///
 369:          /// </summary>
 370:          private static string ProcessRequest2(string url, bool utf8)
 371:          {
 372:              string text = "";
 373:   
 374:              try
 375:              {
 376:                  Uri ourUri = new Uri(url);
 377:                  // Creates an HttpWebRequest for the specified URL. 
 378:                  HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
 379:   
 380:                  //myHttpWebRequest.Method = "POST";
 381:                  //myHttpWebRequest.Timeout = 5000; // 5 sec
 382:                  //myHttpWebRequest.MaximumResponseHeadersLength = 100; // *1024 (Kilobytes)
 383:   
 384:                  // set the range of data to be returned if the start and end positions are given
 385:                  //if (range) myHttpWebRequest.AddRange(start);
 386:   
 387:                  myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
 388:                  myHttpWebRequest.ContentLength = 0;
 389:   
 390:                  HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
 391:   
 392:                  if (myHttpWebRequest.HaveResponse)
 393:                  {
 394:                      Stream receiveStream = myHttpWebResponse.GetResponseStream();
 395:                      Encoding encode;
 396:   
 397:                      if (utf8) encode = System.Text.Encoding.GetEncoding("utf-8");
 398:                      else encode = System.Text.Encoding.GetEncoding(1252); // 1252 best for western char
 399:   
 400:                      // Pipes the stream to a higher level stream reader with the required encoding format. 
 401:                      using (StreamReader readStream = new StreamReader(receiveStream, encode))
 402:                      {
 403:                          text = readStream.ReadToEnd().Trim();  // ONE
 404:   
 405:                          /*
 406:                          // TWO
 407:                          Char[] read = new Char[256];
 408:                          // Reads 256 characters at a time.    
 409:                          int count = readStream.Read( read, 0, 256 );
 410:  
 411:                          while (count > 0) 
 412:                          {
 413:                            // Dumps the 256 characters on a string and displays the string to the console.
 414:                            String str = new String(read, 0, count);
 415:                            text += str;
 416:                            count = readStream.Read(read, 0, 256);
 417:                          }
 418:                          */
 419:   
 420:                          // Releases the resources of the response.
 421:                          //myHttpWebResponse.Close();
 422:                      }
 423:                  }
 424:                  else
 425:                  {
 426:                      text = "\nResponse not received from server";
 427:                  }
 428:              }
 429:              catch (WebException e)
 430:              {
 431:                  HttpWebResponse response = (HttpWebResponse)e.Response;
 432:                  if (response != null)
 433:                  {
 434:                      if (response.StatusCode == HttpStatusCode.Unauthorized)
 435:                      {
 436:                          string challenge = null;
 437:                          challenge = response.GetResponseHeader("WWW-Authenticate");
 438:                          if (challenge != null) text = "\nThe following challenge was raised by the server: " + challenge;
 439:                      }
 440:                      else text = "\nThe following WebException was raised : " + e.Message;
 441:                  }
 442:                  else text = "\nResponse Received from server was null";
 443:              }
 444:              catch (Exception e)
 445:              {
 446:                  text = "\nThe following Exception was raised : " + e.Message;
 447:              }
 448:   
 449:              return text;
 450:          }
 451:   
 452:          ////////////////////////////////////////////////////////////////////////////
 453:   
 454:          /// <summary>
 455:          ///
 456:          /// </summary>
 457:          private static int Get(string url, out string text, out string result)
 458:          {
 459:              int op;
 460:   
 461:              op = 0;
 462:              result = "";
 463:              text = "";
 464:   
 465:              try
 466:              {
 467:                  Uri ourUri = new Uri(url);
 468:                  // Creates an HttpWebRequest for the specified URL. 
 469:                  HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
 470:                  HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
 471:   
 472:                  Stream receiveStream = myHttpWebResponse.GetResponseStream();
 473:                  Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
 474:   
 475:                  // Pipes the stream to a higher level stream reader with the required encoding format. 
 476:                  using (StreamReader readStream = new StreamReader(receiveStream, encode))
 477:                  {
 478:                      Char[] read = new Char[256];
 479:                      // Reads 256 characters at a time.    
 480:                      int count = readStream.Read(read, 0, 256);
 481:   
 482:                      while (count > 0)
 483:                      {
 484:                          // Dumps the 256 characters on a string and displays the string to the console.
 485:                          String str = new String(read, 0, count);
 486:                          text += str;
 487:                          count = readStream.Read(read, 0, 256);
 488:                      }
 489:   
 490:                      // Releases the resources of the response.
 491:                      //myHttpWebResponse.Close();
 492:                  }
 493:   
 494:                  op = 1;
 495:              }
 496:              catch (WebException e)
 497:              {
 498:                  HttpWebResponse response = (HttpWebResponse)e.Response;
 499:                  if (response != null)
 500:                  {
 501:                      if (response.StatusCode == HttpStatusCode.Unauthorized)
 502:                      {
 503:                          string challenge = null;
 504:                          challenge = response.GetResponseHeader("WWW-Authenticate");
 505:                          if (challenge != null) result = "The following challenge was raised by the server: " + challenge;
 506:                      }
 507:                      else result = "The following WebException was raised : " + e.Message;
 508:                  }
 509:                  else result = "Response Received from server was null";
 510:   
 511:                  op = -1;
 512:              }
 513:              catch (Exception e)
 514:              {
 515:                  result = "The following Exception was raised : " + e.Message;
 516:                  op = -1;
 517:              }
 518:   
 519:              return op;
 520:          }
 521:   
 522:          ////////////////////////////////////////////////////////////////////////////
 523:          ////////////////////////////////////////////////////////////////////////////
 524:      }
 525:  }