如何只用C#请求HTTP头?

Jad*_*ias 30 .net c# system.net httpwebrequest

我想检查一个大文件的URL是否存在.我正在使用下面的代码,但它太慢了:

public static bool TryGet(string url)
{
    try
    {
        GetHttpResponseHeaders(url);
        return true;
    }
    catch (WebException)
    {
    }

    return false;
}

public static Dictionary<string, string> GetHttpResponseHeaders(string url)
{
    Dictionary<string, string> headers = new Dictionary<string, string>();
    WebRequest webRequest = HttpWebRequest.Create(url);
    using (WebResponse webResponse = webRequest.GetResponse())
    {
        foreach (string header in webResponse.Headers)
        {
            headers.Add(header, webResponse.Headers[header]);
        }
    }

    return headers;
}
Run Code Online (Sandbox Code Playgroud)

Teo*_*gul 49

你需要设置:

webRequest.Method = "HEAD";
Run Code Online (Sandbox Code Playgroud)

这样,服务器将仅响应头信息(无内容).这对于检查服务器是否接受某些操作(即压缩数据等)也很有用.

  • @Liam我的经验是,它不适用于大量网站,如20% (2认同)