I wrote a class that downloads the HTML of a page from the internet. This class also manages redirects. This works well but I'm not very satisfied about time management for slower servers. In fact, if the website is slow, the method GetHtml
will return an empty string, so how can I optimize this class, to prevent such a situation from happening?
CODE
using System;
using System.IO;
using System.Net;
using System.Net.Http;
namespace SWP.Helpers
{
/// <summary>
/// Download html from an Internet page.
/// </summary>
public class NetworkHelper
{
/// <summary>
/// Store the previous url used in the request.
/// </summary>
private Uri _storedUrl = null;
/// <summary>
/// Store the previous html downloaded.
/// </summary>
private string _storedData = "";
/// <summary>
/// Get the html structure of a site.
/// </summary>
/// <param name="url">Represents the URL of the page where to download the data.</param>
/// <returns>Return a string that contains the html of the site.</returns>
public string GetHtml(Uri url)
{
//If the current url is the same of the older, then will returned the previous html structure, in this way will not be wasted any time to perform another connection.
if (url == _storedUrl)
return _storedData;
else
_storedUrl = url;
//Web request handler.
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
try
{
//Configure the client manager for perform a page compression.
HttpClientHandler handler = new HttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
//Handle the client to manage possible redirect.
HttpClient httpClient = new HttpClient(handler);
//Set the web request.
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = url,
Method = HttpMethod.Get
};
//Get the response.
HttpResponseMessage response = httpClient.SendAsync(request).Result;
//Return the code of the web request.
int statusCode = (int)response.StatusCode;
//If the code is within this range, then the server has executed a redirect.
if (statusCode >= 300 && statusCode <= 399)
{
//Get the new url.
Uri redirectUri = response.Headers.Location;
//Sanitize the url.
if (!redirectUri.IsAbsoluteUri)
{
redirectUri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority) + redirectUri);
}
//Call again this method with the correct url.
return GetHtml(redirectUri);
}
_storedData = response.Content.ReadAsStringAsync().Result;
return _storedData;
}
catch (WebException)
{
throw;
}
}
}
}
as you can see, the logic is really simple, and the method is well commented. Are there any problems I haven't taken into account?
HttpClientHandler
already has the ability to follow redirection responses out of the box withAllowAutoRedirect
property \$\endgroup\$