Advertisement
Guest User

webhelper

a guest
Mar 18th, 2014
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.77 KB | None | 0 0
  1. using GP.Utils.Web;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9.  
  10. namespace GP.Utils
  11. {
  12.     public static class WebHelper
  13.     {
  14.         public static async Task<string> ReadWebContentWithPostAsync(Uri uri, Encoding encoding, string bodyString, string contentType, Action<HttpWebRequest> configurator = null)
  15.         {
  16.             if (encoding == null)
  17.             {
  18.                 throw new ArgumentNullException("encoding");
  19.             }
  20.  
  21.             HttpWebRequest httpRequest = await CreateRequest(uri, bodyString, contentType, configurator);
  22.  
  23.             return await ReadAsync(encoding, httpRequest);
  24.         }
  25.  
  26.         private static async Task<HttpWebRequest> CreateRequest(Uri uri, string bodyString, string contentType, Action<HttpWebRequest> configurator)
  27.         {
  28.             if (bodyString == null)
  29.             {
  30.                 throw new ArgumentNullException("body");
  31.             }
  32.  
  33.             if (contentType == null)
  34.             {
  35.                 throw new ArgumentNullException("contentType");
  36.             }
  37.  
  38.             if (uri == null)
  39.             {
  40.                 throw new ArgumentNullException("uri");
  41.             }
  42.  
  43.             HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
  44.             httpRequest.Method = "POST";
  45.             httpRequest.ContentType = contentType;
  46.             httpRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
  47.  
  48.             if (configurator != null)
  49.             {
  50.                 configurator(httpRequest);
  51.             }
  52.  
  53.             Stream requestStream = await httpRequest.GetRequestStreamAsync();
  54.             try
  55.             {
  56.                 byte[] bodyBytes = Encoding.UTF8.GetBytes(bodyString);
  57.  
  58.                 await requestStream.WriteAsync(bodyBytes, 0, bodyBytes.Length);
  59.             }
  60.             finally
  61.             {
  62.                 if (requestStream != null)
  63.                 {
  64.                     requestStream.Dispose();
  65.                     requestStream = null;
  66.                 }
  67.             }
  68.             return httpRequest;
  69.         }
  70.  
  71.         public static Task<string> ReadWebContentWithPostAsync(string uriString, Encoding encoding, string bodyString, string contentType, Action<HttpWebRequest> configurator = null)
  72.         {
  73.             return ReadWebContentWithPostAsync(new Uri(uriString, UriKind.Absolute), encoding, bodyString, contentType, configurator);
  74.         }
  75.  
  76.         public static async Task<string> ReadWebContentWithFormPostAsync(Uri uri, Encoding encoding, Dictionary<string, object> body, Action<HttpWebRequest> configurator = null)
  77.         {
  78.             if (body == null)
  79.             {
  80.                 throw new ArgumentNullException("body");
  81.             }
  82.             if (encoding == null)
  83.             {
  84.                 throw new ArgumentNullException("encoding");
  85.             }
  86.  
  87.             string bodyString = UrlUtility.BuildUrlEncodedBody(body);
  88.  
  89.             HttpWebRequest httpRequest = await CreateRequest(uri, bodyString, "application/x-www-form-urlencoded; charset=UTF-8", configurator);
  90.  
  91.             return await ReadAsync(encoding, httpRequest);
  92.         }
  93.  
  94.         public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Encoding encoding, Dictionary<string, object> body, Action<HttpWebRequest> configurator = null)
  95.         {
  96.             return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.Absolute), encoding, body, configurator);
  97.         }
  98.  
  99.         public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Encoding encoding, Dictionary<string, object> body)
  100.         {
  101.             return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), encoding, body);
  102.         }        
  103.        
  104.         public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Dictionary<string, object> body, Action<HttpWebRequest> configurator)
  105.         {
  106.             return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8, body, configurator);
  107.         }
  108.  
  109.         public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Dictionary<string, object> body)
  110.         {
  111.             return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8, body, null);
  112.         }
  113.  
  114.         public static async Task<string> ReadWebContentAsync(Uri uri, Encoding encoding, Action<HttpWebRequest> configurator = null)
  115.         {
  116.             if (encoding == null)
  117.             {
  118.                 throw new ArgumentNullException("encoding");
  119.             }
  120.  
  121.             HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
  122.             httpRequest.Method = "GET";
  123.             httpRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
  124.  
  125.             if (configurator != null)
  126.             {
  127.                 configurator(httpRequest);
  128.             }
  129.  
  130.             return await ReadAsync(encoding, httpRequest);
  131.         }
  132.  
  133.         private static async Task<string> ReadAsync(Encoding encoding, HttpWebRequest httpRequest)
  134.         {
  135.             string webContent = null;
  136.  
  137.             WebResponse response = null;
  138.             try
  139.             {
  140.                 response = await httpRequest.GetResponseWithTimeoutAsync();
  141.  
  142.                 Stream responseStream = response.GetResponseStream();
  143.                 try
  144.                 {
  145.                     using (StreamReader reader = new StreamReader(responseStream, encoding))
  146.                     {
  147.                         responseStream = null;
  148.  
  149.                         webContent = await reader.ReadToEndAsync();
  150.                     }
  151.                 }
  152.                 finally
  153.                 {
  154.                     if (responseStream != null)
  155.                     {
  156.                         responseStream.Dispose();
  157.                         responseStream = null;
  158.                     }
  159.                 }
  160.             }
  161.             finally
  162.             {
  163.                 if (response != null)
  164.                 {
  165.                     response.Close();
  166.                 }
  167.             }
  168.  
  169.             return webContent;
  170.         }        
  171.        
  172.         public static Task<string> ReadWebContentAsync(string uriString, Action<HttpWebRequest> configurator = null)
  173.         {
  174.             return ReadWebContentAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8, configurator);
  175.         }
  176.  
  177.         public static Task<string> ReadWebContentAsync(string uriString, Encoding encoding, Action<HttpWebRequest> configurator = null)
  178.         {
  179.             return ReadWebContentAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), encoding, configurator);
  180.         }
  181.  
  182.         public static Task<string> ReadWebContentAsync(string uriString)
  183.         {
  184.             return ReadWebContentAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8);
  185.         }
  186.  
  187.         private static Task<WebResponse> GetResponseWithTimeoutAsync(this WebRequest request)
  188.         {
  189.             if (request == null)
  190.             {
  191.                 throw new ArgumentNullException("request");
  192.             }
  193.  
  194.             bool timeout = false;
  195.  
  196.             TaskCompletionSource<WebResponse> completionSource = new TaskCompletionSource<WebResponse>();
  197.  
  198.             AsyncCallback completedCallback =
  199.                 result =>
  200.                 {
  201.                     try
  202.                     {
  203.                         completionSource.TrySetResult(request.EndGetResponse(result));
  204.                     }
  205.                     catch (WebException ex)
  206.                     {
  207.                         if (timeout)
  208.                         {
  209.                             completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", WebExceptionStatus.Timeout));
  210.                         }
  211.                         else
  212.                         {
  213.                             completionSource.TrySetException(ex);
  214.                         }
  215.                     }
  216.                     catch (Exception ex)
  217.                     {
  218.                         completionSource.TrySetException(ex);
  219.                     }
  220.                 };
  221.  
  222.             IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);
  223.  
  224.             if (!asyncResult.IsCompleted)
  225.             {
  226.                 if (request.Timeout != Timeout.Infinite)
  227.                 {
  228.                     WaitOrTimerCallback timedOutCallback =
  229.                         (object state, bool timedOut) =>
  230.                         {
  231.                             if (timedOut)
  232.                             {
  233.                                 timeout = true;
  234.                                 request.Abort();
  235.                             }
  236.                         };
  237.  
  238.                     ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, request.Timeout, true);
  239.                 }
  240.             }
  241.  
  242.             return completionSource.Task;
  243.         }
  244.  
  245.         /// <summary>
  246.         /// Uses the basic authentication with the specified username and password.
  247.         /// </summary>
  248.         /// <param name="request">The request to enable basic authentication for.</param>
  249.         /// <param name="username">The username for authentication.</param>
  250.         /// <param name="password">The password for authentication.</param>
  251.         public static void UseBasicAuth(this WebRequest request, string username, string password)
  252.         {
  253.             string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
  254.  
  255.             request.Headers["Authorization"] = "Basic " + authInfo;
  256.         }
  257.     }
  258. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement