)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Home » Code Library » Http (Ia.Cl.Model)

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.IO;
    3: using System.Net;
    4: using System.Text;
    5: using System.Threading.Tasks;
    6: using System.Net.Http;
    7: using System.Net.Http.Headers;
    8: using System.Net.Http.Json;
    9: using Newtonsoft.Json;
   10:  
   11: namespace Ia.Cl.Model
   12: {
   13:     ////////////////////////////////////////////////////////////////////////////
   14:  
   15:     /// <summary publish="true">
   16:     /// Contains functions that relate to posting and receiving data from remote Internet/Intranet pages
   17:     /// </summary>
   18:     /// <remarks> 
   19:     /// Copyright � 2001-2020 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
   20:     ///
   21:     /// 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
   22:     /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
   23:     ///
   24:     /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   25:     /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
   26:     /// 
   27:     /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
   28:     /// 
   29:     /// Copyright notice: This notice may not be removed or altered from any source distribution.
   30:     /// </remarks> 
   31:     public class Http
   32:     {
   33:         ////////////////////////////////////////////////////////////////////////////
   34:  
   35:         /// <summary>
   36:         ///
   37:         /// </summary>
   38:         private static bool range = false;
   39:  
   40:         ////////////////////////////////////////////////////////////////////////////
   41:  
   42:         /// <summary>
   43:         ///
   44:         /// </summary>
   45:         public Http() { }
   46:  
   47:         // Note that "https://" and "http://" are different. Wrong protocol could produce a "(403) Forbidden" response.
   48:  
   49:         // Include custom cookies, start and end points, and posting of data to remove server.
   50:  
   51:         // See https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
   52:  
   53:         // Remember to "synch all the way"
   54:  
   55:         ////////////////////////////////////////////////////////////////////////////
   56:  
   57:         /// <summary>
   58:         /// 
   59:         /// </summary>
   60:         public static async Task<string> PostAsync<T>(string baseAddress, string serviceUrl, T t)
   61:         {
   62:             HttpResponseMessage httpResponseMessage;
   63:             var s = string.Empty;
   64:  
   65:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
   66:  
   67:             using (var httpClient = new HttpClient())
   68:             {
   69:                 httpClient.BaseAddress = new Uri(baseAddress);
   70:                 httpClient.DefaultRequestHeaders.Accept.Clear();
   71:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
   72:  
   73:                 HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(t), Encoding.UTF8, "application/json");
   74:  
   75:                 httpResponseMessage = await httpClient.PostAsJsonAsync(serviceUrl, httpContent);
   76:                 // e.g. httpResponseMessage = await httpClient.PostAsJsonAsync("api/products", product);
   77:  
   78:                 httpResponseMessage.EnsureSuccessStatusCode();
   79:  
   80:                 s = await httpResponseMessage.Content.ReadAsStringAsync();
   81:             }
   82:  
   83:             return s;
   84:         }
   85:  
   86:         ////////////////////////////////////////////////////////////////////////////
   87:  
   88:         /// <summary>
   89:         /// 
   90:         /// </summary>
   91:         public static async Task<string> PostAsync(string baseAddress, string serviceUrl)
   92:         {
   93:             HttpResponseMessage httpResponseMessage;
   94:             var s = string.Empty;
   95:  
   96:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
   97:  
   98:             using (var httpClient = new HttpClient())
   99:             {
  100:                 httpClient.BaseAddress = new Uri(baseAddress);
  101:                 httpClient.DefaultRequestHeaders.Accept.Clear();
  102:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  103:  
  104:                 HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(string.Empty), Encoding.UTF8, "application/json"); // dummy
  105:  
  106:                 httpResponseMessage = await httpClient.PostAsJsonAsync(serviceUrl, httpContent);
  107:                 // e.g. httpResponseMessage = await httpClient.PostAsJsonAsync("api/products", product);
  108:  
  109:                 httpResponseMessage.EnsureSuccessStatusCode();
  110:  
  111:                 s = await httpResponseMessage.Content.ReadAsStringAsync();
  112:             }
  113:  
  114:             return s;
  115:         }
  116:  
  117:         ////////////////////////////////////////////////////////////////////////////
  118:  
  119:         /// <summary>
  120:         /// 
  121:         /// </summary>
  122:         public static async Task<T> GetAsync<T>(string baseAddress, string serviceUrl)
  123:         {
  124:             HttpResponseMessage httpResponseMessage;
  125:             T t;
  126:  
  127:             t = default;
  128:  
  129:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
  130:  
  131:             using (var httpClient = new HttpClient())
  132:             {
  133:                 httpClient.BaseAddress = new Uri(baseAddress);
  134:                 httpClient.DefaultRequestHeaders.Accept.Clear();
  135:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  136:  
  137:                 httpResponseMessage = await httpClient.GetAsync(serviceUrl);
  138:  
  139:                 if (httpResponseMessage.IsSuccessStatusCode)
  140:                 {
  141:                     t = await httpResponseMessage.Content.ReadFromJsonAsync<T>(); //.ReadAsAsync<T>();
  142:                     // see https://stackoverflow.com/questions/63108280/has-httpcontent-readasasynct-method-been-superceded-in-net-core
  143:                 }
  144:                 else
  145:                 {
  146:  
  147:                 }
  148:             }
  149:  
  150:             return t;
  151:         }
  152:  
  153:         ////////////////////////////////////////////////////////////////////////////
  154:  
  155:         /// <summary>
  156:         /// 
  157:         /// </summary>
  158:         public static async Task<string> GetAsync(string baseAddress, string serviceUrl)
  159:         {
  160:             HttpResponseMessage httpResponseMessage;
  161:             var s = string.Empty;
  162:  
  163:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
  164:  
  165:             using (var httpClient = new HttpClient())
  166:             {
  167:                 httpClient.BaseAddress = new Uri(baseAddress);
  168:                 httpClient.DefaultRequestHeaders.Accept.Clear();
  169:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  170:  
  171:                 httpResponseMessage = await httpClient.GetAsync(serviceUrl);
  172:  
  173:                 httpResponseMessage.EnsureSuccessStatusCode();
  174:  
  175:                 s = await httpResponseMessage.Content.ReadAsStringAsync();
  176:             }
  177:  
  178:             return s;
  179:         }
  180:  
  181:         ////////////////////////////////////////////////////////////////////////////
  182:  
  183:         /// <summary>
  184:         /// 
  185:         /// </summary>
  186:         public static async Task<string> PutAsync<T>(string baseAddress, string serviceUrl, T t)
  187:         {
  188:             HttpResponseMessage httpResponseMessage;
  189:             var s = string.Empty;
  190:  
  191:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
  192:  
  193:             using (var httpClient = new HttpClient())
  194:             {
  195:                 httpClient.BaseAddress = new Uri(baseAddress);
  196:                 httpClient.DefaultRequestHeaders.Accept.Clear();
  197:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  198:  
  199:                 HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(t), Encoding.UTF8, "application/json");
  200:  
  201:                 httpResponseMessage = await httpClient.PutAsJsonAsync(serviceUrl, httpContent);
  202:                 // e.g. httpResponseMessage = await httpClient.PutAsJsonAsync($"api/products/{product.Id}", product);
  203:  
  204:                 httpResponseMessage.EnsureSuccessStatusCode();
  205:  
  206:                 s = await httpResponseMessage.Content.ReadAsStringAsync();
  207:             }
  208:  
  209:             return s;
  210:         }
  211:  
  212:         ////////////////////////////////////////////////////////////////////////////
  213:  
  214:         /// <summary>
  215:         /// 
  216:         /// </summary>
  217:         public static async Task<string> PutAsync(string baseAddress, string serviceUrl)
  218:         {
  219:             HttpResponseMessage httpResponseMessage;
  220:             var s = string.Empty;
  221:  
  222:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
  223:  
  224:             using (var httpClient = new HttpClient())
  225:             {
  226:                 httpClient.BaseAddress = new Uri(baseAddress);
  227:                 httpClient.DefaultRequestHeaders.Accept.Clear();
  228:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  229:  
  230:                 HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(string.Empty), Encoding.UTF8, "application/json"); // dummy
  231:  
  232:                 httpResponseMessage = await httpClient.PutAsJsonAsync(serviceUrl, httpContent);
  233:                 // e.g. httpResponseMessage = await httpClient.PutAsJsonAsync($"api/products/{product.Id}", product);
  234:  
  235:                 httpResponseMessage.EnsureSuccessStatusCode();
  236:  
  237:                 s = await httpResponseMessage.Content.ReadAsStringAsync();
  238:             }
  239:  
  240:             return s;
  241:         }
  242:  
  243:         ////////////////////////////////////////////////////////////////////////////
  244:  
  245:         /// <summary>
  246:         /// 
  247:         /// </summary>
  248:         public static async Task<string> DeleteAsync(string baseAddress, string serviceUrl)
  249:         {
  250:             HttpResponseMessage httpResponseMessage;
  251:             var s = string.Empty;
  252:  
  253:             serviceUrl = SuffixUrlWithSlashIfItContainsDot(serviceUrl);
  254:  
  255:             using (var httpClient = new HttpClient())
  256:             {
  257:                 httpClient.BaseAddress = new Uri(baseAddress);
  258:                 httpClient.DefaultRequestHeaders.Accept.Clear();
  259:                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  260:  
  261:                 httpResponseMessage = await httpClient.DeleteAsync(serviceUrl);
  262:                 // e.g. httpResponseMessage = await client.DeleteAsync($"api/products/{id}");
  263:  
  264:                 httpResponseMessage.EnsureSuccessStatusCode();
  265:  
  266:                 s = await httpResponseMessage.Content.ReadAsStringAsync();
  267:             }
  268:  
  269:             return s;
  270:         }
  271:  
  272:         ////////////////////////////////////////////////////////////////////////////
  273:  
  274:         /// <summary>
  275:         ///
  276:         /// </summary>
  277:         private static string SuffixUrlWithSlashIfItContainsDot(string url)
  278:         {
  279:             // - Suffix the URL with a slash e.g. http://somedomain.com/api/people/staff.33311/ instead of http://somedomain.com/api/people/staff.33311 to pass a dot '.'
  280:  
  281:             if (!string.IsNullOrEmpty(url))
  282:             {
  283:                 if (url.Contains(".")) url += "/";
  284:             }
  285:  
  286:             return url;
  287:         }
  288:  
  289:         ////////////////////////////////////////////////////////////////////////////
  290:         ////////////////////////////////////////////////////////////////////////////
  291:  
  292:  
  293:  
  294:         ////////////////////////////////////////////////////////////////////////////
  295:         ////////////////////////////////////////////////////////////////////////////
  296:  
  297:         /// <summary>
  298:         ///
  299:         /// </summary>
  300:         public static string Request(string url)
  301:         {
  302:             range = false;
  303:  
  304:             return ProcessRequest(url, 0, false, null, null);
  305:         }
  306:  
  307:         ////////////////////////////////////////////////////////////////////////////
  308:  
  309:         /// <summary>
  310:         ///
  311:         /// </summary>
  312:         public static string Request(string url, int start)
  313:         {
  314:             range = true;
  315:  
  316:             return ProcessRequest(url, start, false, null, null);
  317:         }
  318:  
  319:         ////////////////////////////////////////////////////////////////////////////
  320:  
  321:         /// <summary>
  322:         ///
  323:         /// </summary>
  324:         public static string Request2(string url)
  325:         {
  326:             range = true;
  327:  
  328:             return ProcessRequest2(url, false);
  329:         }
  330:  
  331:         ////////////////////////////////////////////////////////////////////////////
  332:  
  333:         /// <summary>
  334:         ///
  335:         /// </summary>
  336:         public static string Request_Utf8(string url, int start)
  337:         {
  338:             range = true;
  339:  
  340:             return ProcessRequest(url, start, true, null, null);
  341:         }
  342:  
  343:         ////////////////////////////////////////////////////////////////////////////
  344:  
  345:         /// <summary>
  346:         ///
  347:         /// </summary>
  348:         public static string Request(string url, int start, System.Net.Cookie c)
  349:         {
  350:             range = true;
  351:  
  352:             return ProcessRequest(url, start, false, c, null);
  353:         }
  354:  
  355:         ////////////////////////////////////////////////////////////////////////////
  356:  
  357:         /// <summary>
  358:         ///
  359:         /// </summary>
  360:         public static string Request(string url, int start, System.Net.Cookie c1, System.Net.Cookie c2)
  361:         {
  362:             range = true;
  363:  
  364:             return ProcessRequest(url, start, false, c1, c2);
  365:         }
  366:  
  367:         ////////////////////////////////////////////////////////////////////////////
  368:  
  369:         /// <summary>
  370:         ///
  371:         /// </summary>
  372:         public static string Post(string URI, string Parameters)
  373:         {
  374:             System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
  375:             //req.Proxy = new System.Net.WebProxy(ProxyString, true);
  376:  
  377:             req.ContentType = "application/x-www-form-urlencoded";
  378:             req.Method = "POST";
  379:             //req.Timeout = 3000;
  380:  
  381:             byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
  382:             req.ContentLength = bytes.Length;
  383:  
  384:             using (System.IO.Stream os = req.GetRequestStream())
  385:             {
  386:                 os.Write(bytes, 0, bytes.Length);
  387:                 //os.Close();
  388:             }
  389:  
  390:             System.Net.WebResponse resp = null;
  391:  
  392:             try
  393:             {
  394:                 resp = req.GetResponse();
  395:  
  396:                 if (resp == null) return null;
  397:  
  398:                 System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(1256));
  399:                 return sr.ReadToEnd().Trim();
  400:             }
  401:             catch (WebException ex)
  402:             {
  403:                 string str = ex.Message;
  404:             }
  405:  
  406:             return null;
  407:         }
  408:  
  409:         ////////////////////////////////////////////////////////////////////////////
  410:  
  411:         /// <summary>
  412:         ///
  413:         /// </summary>
  414:         public static string Post(string URI, string Parameters, int code_page)
  415:         {
  416:             // Sometimes you need to POST in Windows 1256 code page for the process to run
  417:  
  418:             System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
  419:             //req.Proxy = new System.Net.WebProxy(ProxyString, true);
  420:  
  421:             req.ContentType = "application/x-www-form-urlencoded";
  422:             req.Method = "POST";
  423:             //req.Timeout = 3000;
  424:  
  425:             byte[] bytes = System.Text.Encoding.GetEncoding(code_page).GetBytes(Parameters);
  426:             req.ContentLength = bytes.Length;
  427:  
  428:             using (System.IO.Stream os = req.GetRequestStream())
  429:             {
  430:                 os.Write(bytes, 0, bytes.Length);
  431:                 //os.Close();
  432:             }
  433:  
  434:             System.Net.WebResponse resp = null;
  435:  
  436:             try
  437:             {
  438:                 resp = req.GetResponse();
  439:  
  440:                 if (resp == null) return null;
  441:  
  442:                 System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(code_page));
  443:                 return sr.ReadToEnd().Trim();
  444:             }
  445:             catch (WebException ex)
  446:             {
  447:                 string str = ex.Message;
  448:             }
  449:  
  450:             return null;
  451:         }
  452:  
  453:         ////////////////////////////////////////////////////////////////////////////
  454:  
  455:         /// <summary>
  456:         ///
  457:         /// </summary>
  458:         private static string ProcessRequest(string url, int start, bool utf8, System.Net.Cookie c1, System.Net.Cookie c2)
  459:         {
  460:             string text = "";
  461:  
  462:             try
  463:             {
  464:                 Uri ourUri = new Uri(url);
  465:                 // Creates an HttpWebRequest for the specified URL. 
  466:                 HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
  467:  
  468:                 // this code below is very important. It sends a request with a specific cookie in the collection
  469:                 // to demonstrate to the remote server that we have his cookie and we should skip his advertisement.
  470:                 if (c1 != null || c2 != null)
  471:                 {
  472:                     myHttpWebRequest.CookieContainer = new CookieContainer();
  473:                     if (c1 != null) myHttpWebRequest.CookieContainer.Add(c1);
  474:                     if (c2 != null) myHttpWebRequest.CookieContainer.Add(c2);
  475:                 }
  476:  
  477:                 myHttpWebRequest.Method = "POST";
  478:                 //myHttpWebRequest.Timeout = 5000; // 5 sec
  479:                 //myHttpWebRequest.MaximumResponseHeadersLength = 100; // *1024 (Kilobytes)
  480:  
  481:                 // set the range of data to be returned if the start and end positions are given
  482:                 if (range) myHttpWebRequest.AddRange(start);
  483:  
  484:                 myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
  485:                 myHttpWebRequest.ContentLength = 0;
  486:  
  487:                 HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
  488:  
  489:                 if (myHttpWebRequest.HaveResponse)
  490:                 {
  491:                     Stream receiveStream = myHttpWebResponse.GetResponseStream();
  492:                     Encoding encode;
  493:  
  494:                     if (utf8) encode = System.Text.Encoding.GetEncoding("utf-8");
  495:                     else encode = System.Text.Encoding.GetEncoding(1252); // 1252 best for western char
  496:  
  497:                     // Pipes the stream to a higher level stream reader with the required encoding format. 
  498:                     using (StreamReader readStream = new StreamReader(receiveStream, encode))
  499:                     {
  500:                         text = readStream.ReadToEnd().Trim();  // ONE
  501:  
  502:                         /*
  503:                         // TWO
  504:                         Char[] read = new Char[256];
  505:                         // Reads 256 characters at a time.    
  506:                         int count = readStream.Read( read, 0, 256 );
  507: 
  508:                         while (count > 0) 
  509:                         {
  510:                           // Dumps the 256 characters on a string and displays the string to the console.
  511:                           String str = new String(read, 0, count);
  512:                           text += str;
  513:                           count = readStream.Read(read, 0, 256);
  514:                         }
  515:                         */
  516:  
  517:                         // Releases the resources of the response.
  518:                         //myHttpWebResponse.Close();
  519:                     }
  520:                 }
  521:                 else
  522:                 {
  523:                     text = "\nResponse not received from server";
  524:                 }
  525:             }
  526:             catch (WebException e)
  527:             {
  528:                 HttpWebResponse response = (HttpWebResponse)e.Response;
  529:                 if (response != null)
  530:                 {
  531:                     if (response.StatusCode == HttpStatusCode.Unauthorized)
  532:                     {
  533:                         string challenge = null;
  534:                         challenge = response.GetResponseHeader("WWW-Authenticate");
  535:                         if (challenge != null) text = "\nThe following challenge was raised by the server: " + challenge;
  536:                     }
  537:                     else text = "\nThe following WebException was raised : " + e.Message;
  538:                 }
  539:                 else text = "\nResponse Received from server was null";
  540:             }
  541:             catch (Exception e)
  542:             {
  543:                 text = "\nThe following Exception was raised : " + e.Message;
  544:             }
  545:  
  546:             return text;
  547:         }
  548:  
  549:         ////////////////////////////////////////////////////////////////////////////
  550:  
  551:         /// <summary>
  552:         ///
  553:         /// </summary>
  554:         private static string ProcessRequest2(string url, bool utf8)
  555:         {
  556:             string text = "";
  557:  
  558:             try
  559:             {
  560:                 Uri ourUri = new Uri(url);
  561:                 // Creates an HttpWebRequest for the specified URL. 
  562:                 HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
  563:  
  564:                 //myHttpWebRequest.Method = "POST";
  565:                 //myHttpWebRequest.Timeout = 5000; // 5 sec
  566:                 //myHttpWebRequest.MaximumResponseHeadersLength = 100; // *1024 (Kilobytes)
  567:  
  568:                 // set the range of data to be returned if the start and end positions are given
  569:                 //if (range) myHttpWebRequest.AddRange(start);
  570:  
  571:                 myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
  572:                 myHttpWebRequest.ContentLength = 0;
  573:  
  574:                 HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
  575:  
  576:                 if (myHttpWebRequest.HaveResponse)
  577:                 {
  578:                     Stream receiveStream = myHttpWebResponse.GetResponseStream();
  579:                     Encoding encode;
  580:  
  581:                     if (utf8) encode = System.Text.Encoding.GetEncoding("utf-8");
  582:                     else encode = System.Text.Encoding.GetEncoding(1252); // 1252 best for western char
  583:  
  584:                     // Pipes the stream to a higher level stream reader with the required encoding format. 
  585:                     using (StreamReader readStream = new StreamReader(receiveStream, encode))
  586:                     {
  587:                         text = readStream.ReadToEnd().Trim();  // ONE
  588:  
  589:                         /*
  590:                         // TWO
  591:                         Char[] read = new Char[256];
  592:                         // Reads 256 characters at a time.    
  593:                         int count = readStream.Read( read, 0, 256 );
  594: 
  595:                         while (count > 0) 
  596:                         {
  597:                           // Dumps the 256 characters on a string and displays the string to the console.
  598:                           String str = new String(read, 0, count);
  599:                           text += str;
  600:                           count = readStream.Read(read, 0, 256);
  601:                         }
  602:                         */
  603:  
  604:                         // Releases the resources of the response.
  605:                         //myHttpWebResponse.Close();
  606:                     }
  607:                 }
  608:                 else
  609:                 {
  610:                     text = "\nResponse not received from server";
  611:                 }
  612:             }
  613:             catch (WebException e)
  614:             {
  615:                 HttpWebResponse response = (HttpWebResponse)e.Response;
  616:                 if (response != null)
  617:                 {
  618:                     if (response.StatusCode == HttpStatusCode.Unauthorized)
  619:                     {
  620:                         string challenge = null;
  621:                         challenge = response.GetResponseHeader("WWW-Authenticate");
  622:                         if (challenge != null) text = "\nThe following challenge was raised by the server: " + challenge;
  623:                     }
  624:                     else text = "\nThe following WebException was raised : " + e.Message;
  625:                 }
  626:                 else text = "\nResponse Received from server was null";
  627:             }
  628:             catch (Exception e)
  629:             {
  630:                 text = "\nThe following Exception was raised : " + e.Message;
  631:             }
  632:  
  633:             return text;
  634:         }
  635:  
  636:         ////////////////////////////////////////////////////////////////////////////
  637:  
  638:         /// <summary>
  639:         ///
  640:         /// </summary>
  641:         private static int Get(string url, out string text, out string result)
  642:         {
  643:             int op;
  644:  
  645:             op = 0;
  646:             result = "";
  647:             text = "";
  648:  
  649:             try
  650:             {
  651:                 Uri ourUri = new Uri(url);
  652:                 // Creates an HttpWebRequest for the specified URL. 
  653:                 HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
  654:                 HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
  655:  
  656:                 Stream receiveStream = myHttpWebResponse.GetResponseStream();
  657:                 Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
  658:  
  659:                 // Pipes the stream to a higher level stream reader with the required encoding format. 
  660:                 using (StreamReader readStream = new StreamReader(receiveStream, encode))
  661:                 {
  662:                     Char[] read = new Char[256];
  663:                     // Reads 256 characters at a time.    
  664:                     int count = readStream.Read(read, 0, 256);
  665:  
  666:                     while (count > 0)
  667:                     {
  668:                         // Dumps the 256 characters on a string and displays the string to the console.
  669:                         String str = new String(read, 0, count);
  670:                         text += str;
  671:                         count = readStream.Read(read, 0, 256);
  672:                     }
  673:  
  674:                     // Releases the resources of the response.
  675:                     //myHttpWebResponse.Close();
  676:                 }
  677:  
  678:                 op = 1;
  679:             }
  680:             catch (WebException e)
  681:             {
  682:                 HttpWebResponse response = (HttpWebResponse)e.Response;
  683:                 if (response != null)
  684:                 {
  685:                     if (response.StatusCode == HttpStatusCode.Unauthorized)
  686:                     {
  687:                         string challenge = null;
  688:                         challenge = response.GetResponseHeader("WWW-Authenticate");
  689:                         if (challenge != null) result = "The following challenge was raised by the server: " + challenge;
  690:                     }
  691:                     else result = "The following WebException was raised : " + e.Message;
  692:                 }
  693:                 else result = "Response Received from server was null";
  694:  
  695:                 op = -1;
  696:             }
  697:             catch (Exception e)
  698:             {
  699:                 result = "The following Exception was raised : " + e.Message;
  700:                 op = -1;
  701:             }
  702:  
  703:             return op;
  704:         }
  705:  
  706:         ////////////////////////////////////////////////////////////////////////////
  707:         ////////////////////////////////////////////////////////////////////////////
  708:     }
  709: }