I built a class which uses an HttpClient instance for downloading the content of a page. This is working pretty well but I'm not really satisfied about my implementation of redirect.
In fact, I handle the redirect manually as you can see:
/// <summary>
/// Web request handler
/// </summary>
public class NetworkHelper
{
/// <summary>
/// Store the url.
/// </summary>
private static Uri _storedUrl = null;
/// <summary>
/// Store the html data.
/// </summary>
private static string _storedData = "";
public static string GetHtml(Uri url)
{
if (url == _storedUrl)
return _storedData;
else
_storedUrl = url;
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
try
{
HttpClientHandler handler = new HttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = url,
Method = HttpMethod.Get
};
HttpResponseMessage response = httpClient.SendAsync(request).Result;
int statusCode = (int)response.StatusCode;
if (statusCode >= 300 && statusCode <= 399)
{
Uri redirectUri = response.Headers.Location;
if (!redirectUri.IsAbsoluteUri)
{
redirectUri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority) + redirectUri);
}
return GetHtml(redirectUri);
}
using (WebClient wClient = new WebClient())
{
wClient.Encoding = System.Text.Encoding.UTF8;
_storedData = wClient.DownloadString(url);
}
return _storedData;
}
catch (WebException)
{
throw;
}
}
}
How can I improve my implementation for handling the redirect?