简体   繁体   English

如何仅请求 HTTP header 和 C#?

[英]How to request only the HTTP header with C#?

I want to check if the URL of a large file exists.我想检查一个大文件的URL是否存在。 I'm using the code below but it is too slow:我正在使用下面的代码,但它太慢了:

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;
}

You need to set:你需要设置:

webRequest.Method = "HEAD";

This way the server will respond with the header information only (no content).这样,服务器将仅响应 header 信息(无内容)。 This is also useful to check if the server accepts certain operations (ie compressed data etc.).这对于检查服务器是否接受某些操作(即压缩数据等)也很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM