I need to detect a type of content located on specific URL. So I created a method to get the Content-Type of response. For small files and HTML pages it works without problems, but if URL points to a big file, request takes a long time - it fetches entire content (file) on background. So, it is possible to cancel request and return result immediately after teh Content-Type
header is received?
My current implementation:
public async static Task<string> GetContentType(string url)
{
try
{
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.Headers.ContentType.MediaType;
}
}
catch (HttpRequestException)
{
return null;
}
}
Since not all servers respond to the HEAD request as expected, you can also use this overload of GetAsync method so that the method returns immediately after headers are received if you use HttpCompletionOption.ResponseHeadersRead as second argument.
An HTTP completion option value that indicates when the operation should be considered completed.
ResponseHeadersRead from MSDN:
The operation should complete as soon as a response is available and headers are read. The content is not read yet.
Then you can dispose the client if you need to.
// Send request to get headers
response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
// Check status code
if (!response.IsSuccessStatusCode) {
// Error...
}
// Get Content Headers
HttpContentHeaderCollection contentHeaders = response.Content.Headers;
// Make decision and dispose client if you wish
if (...) {
client.Dispose();
}
Now how about
var response = await client.SendAsync(
new HttpRequestMessage(HttpMethod.Head, url)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With