Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取网址的内容类型?_C#_.net_C# 4.0_Content Type - Fatal编程技术网

C# 如何获取网址的内容类型?

C# 如何获取网址的内容类型?,c#,.net,c#-4.0,content-type,C#,.net,C# 4.0,Content Type,我想得到一个网址的类型。例如,一个Html页面,其页面类型为text/Html,但其类型为text/xml。页面的类型似乎是image/png,但它是text/html 我想知道如何检测网址的内容类型,如?HTTP响应头:内容类型 要获得更详细的响应,请提供更详细的问题。您可以通过响应的Http标头检测内容类型,因为标头是 Connection:keep-alive Content-Encoding:gzip Content-Type:text/html; charset=utf-8 Date:

我想得到一个网址的类型。例如,一个Html页面,其页面类型为
text/Html
,但其类型为
text/xml
。页面的类型似乎是
image/png
,但它是
text/html


我想知道如何检测网址的内容类型,如?

HTTP响应头:
内容类型


要获得更详细的响应,请提供更详细的问题。

您可以通过响应的Http标头检测
内容类型,因为标头是

Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=utf-8
Date:Tue, 14 Aug 2012 03:01:41 GMT
Server:bws
Transfer-Encoding:chunked
Vary:Accept-Encoding

将从标题中获取mime类型,而无需下载页面。只需在响应标题中查找内容类型。

应该是这样的

    var request = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest;
    if (request != null)
    {
        var response = request.GetResponse() as HttpWebResponse;

        string contentType = "";

        if (response != null)
            contentType = response.ContentType;
    }

阅读HTTP标题

HTTP头将告诉您内容类型。例如:

内容类型:application/xml

有两种方法可以确定内容类型

  • URL调用的文件扩展名
  • http头内容类型
  • 第一个是微软在过去的日子里推广的,现在已经不是一个好的做法了

    如果客户机具有仅接受特定内容类型的显示约束,它将使用如下标题请求服务器

    accept: application/json
    accept: text/html
    accept: application/xml
    
    然后,如果服务器可以提供其中一个并选择XML,它将返回带有标题的内容

    content-type: application/xml.
    
    但是,有些服务包括进一步的信息,如

    content-type: application/xml; charset=utf-8
    

    而不是使用自己的头进行字符编码。

    不应该这样。URL在标题中是否有内容类型。OP询问如何在C#中获取该信息,而不是标题是什么。OP询问如何在C#中获取该信息,而不是标题是什么。大概
    MyClient
    WebClient
    的子类,具有
    HEAD
    支持?是的,您是正确的。这是从我用于检查二进制http响应的另一个示例复制而来的。如果您链接到另一个示例,可能会对读者有用:)带有方法支持-我还使用了您的代码,谢谢。
    request.method=“HEAD”可短接到
    contentType=response?.contentType()
    
    content-type: application/xml; charset=utf-8