Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using GP.Utils.Web;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace GP.Utils
- {
- public static class WebHelper
- {
- public static async Task<string> ReadWebContentWithPostAsync(Uri uri, Encoding encoding, string bodyString, string contentType, Action<HttpWebRequest> configurator = null)
- {
- if (encoding == null)
- {
- throw new ArgumentNullException("encoding");
- }
- HttpWebRequest httpRequest = await CreateRequest(uri, bodyString, contentType, configurator);
- return await ReadAsync(encoding, httpRequest);
- }
- private static async Task<HttpWebRequest> CreateRequest(Uri uri, string bodyString, string contentType, Action<HttpWebRequest> configurator)
- {
- if (bodyString == null)
- {
- throw new ArgumentNullException("body");
- }
- if (contentType == null)
- {
- throw new ArgumentNullException("contentType");
- }
- if (uri == null)
- {
- throw new ArgumentNullException("uri");
- }
- HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
- httpRequest.Method = "POST";
- httpRequest.ContentType = contentType;
- httpRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
- if (configurator != null)
- {
- configurator(httpRequest);
- }
- Stream requestStream = await httpRequest.GetRequestStreamAsync();
- try
- {
- byte[] bodyBytes = Encoding.UTF8.GetBytes(bodyString);
- await requestStream.WriteAsync(bodyBytes, 0, bodyBytes.Length);
- }
- finally
- {
- if (requestStream != null)
- {
- requestStream.Dispose();
- requestStream = null;
- }
- }
- return httpRequest;
- }
- public static Task<string> ReadWebContentWithPostAsync(string uriString, Encoding encoding, string bodyString, string contentType, Action<HttpWebRequest> configurator = null)
- {
- return ReadWebContentWithPostAsync(new Uri(uriString, UriKind.Absolute), encoding, bodyString, contentType, configurator);
- }
- public static async Task<string> ReadWebContentWithFormPostAsync(Uri uri, Encoding encoding, Dictionary<string, object> body, Action<HttpWebRequest> configurator = null)
- {
- if (body == null)
- {
- throw new ArgumentNullException("body");
- }
- if (encoding == null)
- {
- throw new ArgumentNullException("encoding");
- }
- string bodyString = UrlUtility.BuildUrlEncodedBody(body);
- HttpWebRequest httpRequest = await CreateRequest(uri, bodyString, "application/x-www-form-urlencoded; charset=UTF-8", configurator);
- return await ReadAsync(encoding, httpRequest);
- }
- public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Encoding encoding, Dictionary<string, object> body, Action<HttpWebRequest> configurator = null)
- {
- return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.Absolute), encoding, body, configurator);
- }
- public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Encoding encoding, Dictionary<string, object> body)
- {
- return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), encoding, body);
- }
- public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Dictionary<string, object> body, Action<HttpWebRequest> configurator)
- {
- return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8, body, configurator);
- }
- public static Task<string> ReadWebContentWithFormPostAsync(string uriString, Dictionary<string, object> body)
- {
- return ReadWebContentWithFormPostAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8, body, null);
- }
- public static async Task<string> ReadWebContentAsync(Uri uri, Encoding encoding, Action<HttpWebRequest> configurator = null)
- {
- if (encoding == null)
- {
- throw new ArgumentNullException("encoding");
- }
- HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
- httpRequest.Method = "GET";
- httpRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
- if (configurator != null)
- {
- configurator(httpRequest);
- }
- return await ReadAsync(encoding, httpRequest);
- }
- private static async Task<string> ReadAsync(Encoding encoding, HttpWebRequest httpRequest)
- {
- string webContent = null;
- WebResponse response = null;
- try
- {
- response = await httpRequest.GetResponseWithTimeoutAsync();
- Stream responseStream = response.GetResponseStream();
- try
- {
- using (StreamReader reader = new StreamReader(responseStream, encoding))
- {
- responseStream = null;
- webContent = await reader.ReadToEndAsync();
- }
- }
- finally
- {
- if (responseStream != null)
- {
- responseStream.Dispose();
- responseStream = null;
- }
- }
- }
- finally
- {
- if (response != null)
- {
- response.Close();
- }
- }
- return webContent;
- }
- public static Task<string> ReadWebContentAsync(string uriString, Action<HttpWebRequest> configurator = null)
- {
- return ReadWebContentAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8, configurator);
- }
- public static Task<string> ReadWebContentAsync(string uriString, Encoding encoding, Action<HttpWebRequest> configurator = null)
- {
- return ReadWebContentAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), encoding, configurator);
- }
- public static Task<string> ReadWebContentAsync(string uriString)
- {
- return ReadWebContentAsync(new Uri(uriString, UriKind.RelativeOrAbsolute), Encoding.UTF8);
- }
- private static Task<WebResponse> GetResponseWithTimeoutAsync(this WebRequest request)
- {
- if (request == null)
- {
- throw new ArgumentNullException("request");
- }
- bool timeout = false;
- TaskCompletionSource<WebResponse> completionSource = new TaskCompletionSource<WebResponse>();
- AsyncCallback completedCallback =
- result =>
- {
- try
- {
- completionSource.TrySetResult(request.EndGetResponse(result));
- }
- catch (WebException ex)
- {
- if (timeout)
- {
- completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", WebExceptionStatus.Timeout));
- }
- else
- {
- completionSource.TrySetException(ex);
- }
- }
- catch (Exception ex)
- {
- completionSource.TrySetException(ex);
- }
- };
- IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);
- if (!asyncResult.IsCompleted)
- {
- if (request.Timeout != Timeout.Infinite)
- {
- WaitOrTimerCallback timedOutCallback =
- (object state, bool timedOut) =>
- {
- if (timedOut)
- {
- timeout = true;
- request.Abort();
- }
- };
- ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, request.Timeout, true);
- }
- }
- return completionSource.Task;
- }
- /// <summary>
- /// Uses the basic authentication with the specified username and password.
- /// </summary>
- /// <param name="request">The request to enable basic authentication for.</param>
- /// <param name="username">The username for authentication.</param>
- /// <param name="password">The password for authentication.</param>
- public static void UseBasicAuth(this WebRequest request, string username, string password)
- {
- string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
- request.Headers["Authorization"] = "Basic " + authInfo;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement