Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient - detect Content-Type [duplicate]

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;
        }
    }
like image 946
Dominik Palo Avatar asked Jan 19 '16 13:01

Dominik Palo


2 Answers

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();
}
like image 105
Mehrzad Chehraz Avatar answered Nov 01 '22 22:11

Mehrzad Chehraz


Now how about

var response = await client.SendAsync(
  new HttpRequestMessage(HttpMethod.Head, url)
);
like image 29
Yam Marcovic Avatar answered Nov 01 '22 22:11

Yam Marcovic