HttpClient - 检测内容类型

Dom*_*alo 8 .net c# content-type dotnet-httpclient

我需要检测位于特定URL上的一种内容.所以我创建了一个获取Content-Type响应的方法.对于小文件和HTML页面,它可以正常工作,但如果URL指向一个大文件,请求需要很长时间 - 它在后台获取整个内容(文件).那么,有可能在Content-Type收到标题后立即取消请求并返回结果?

我目前的实施:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Meh*_*raz 5

由于并非所有服务器都按预期响应HEAD请求,因此您还可以使用此GetAsync方法的重载,以便在使用HttpCompletionOption.ResponseHeadersRead作为第二个参数时,方法在收到标头后立即返回.

HTTP完成选项值,指示何时应该认为操作已完成.

来自MSDN的ResponseHeadersRead:

一旦响应可用并且读取标题,操作就应该完成.内容尚未阅读.

然后,如果需要,您可以处置客户端.

// 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();
}
Run Code Online (Sandbox Code Playgroud)


Yam*_*vic 4

现在怎么样

var response = await client.SendAsync(
  new HttpRequestMessage(HttpMethod.Head, url)
);
Run Code Online (Sandbox Code Playgroud)