如何申请只用C#HTTP头? [英] How to request only the HTTP header with C#?

查看:113
本文介绍了如何申请只用C#HTTP头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查,如果一个大文件的URL存在。我使用下面的代码,但实在是太慢了:

 公共静态布尔TryGet(字符串URL)
{

{
GetHttpResponseHeaders(URL);
返回真;
}
赶上(引发WebException)
{
}

返回FALSE;
}

公共静态字典<字符串,字符串> GetHttpResponseHeaders(字符串URL)
{
&字典LT;字符串,字符串>标题=新词典<字符串,字符串>();
的WebRequest的WebRequest = HttpWebRequest.Create(URL);
使用(WebResponse类WebResponse类= webRequest.GetResponse())
{
的foreach(在webResponse.Headers串标头)
{
headers.Add(头,WebResponse类。头[标题]);
}
}

返回头;
}


解决方案

您需要设置:

  webRequest.Method =HEAD; 



这样服务器将与头信息只(无内容)响应。这也是有用以检查服务器接受特定操​​作(即,压缩数据等)。


I want to check if the URL of a large file exists. 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). This is also useful to check if the server accepts certain operations (i.e. compressed data etc.).

这篇关于如何申请只用C#HTTP头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆