繁体   English   中英

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

[英]How to get content type of a web address?

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

我想知道我怎么可以检测如Web地址的内容类型

它应该是这样的

    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响应标头: content-type

如需更详细的回复,请提供更详细的问题。

您可以通过响应的Http标头检测Content-Type ,对于http://bayanbox.ir/user/ahmadalli/images/div.png ,标题是

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

阅读HTTP标头。

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

content-type:application / xml。

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

  1. URL调用的文件扩展名
  2. http标头内容类型

第一个是微软在过去的某种程度上推广的,并且不再是一个好的做法。

如果客户端具有仅接受某种内容类型的显示约束,则它将向服务器请求标题

accept: application/json
accept: text/html
accept: application/xml

然后,如果服务器可以提供其中一个并选择XML,它将返回带有标头的内容

content-type: application/xml.

但是,某些服务包括更多信息

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

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

using (MyClient client = new MyClient())
    {
        client.HeadOnly = true;
        string uri = "http://www.google.com";
        byte[] body = client.DownloadData(uri); // note should be 0-length
        string type = client.ResponseHeaders["content-type"];
        client.HeadOnly = false;
        // check 'tis not binary... we'll use text/, but could
        // check for text/html
        if (type.StartsWith(@"text/"))
        {
            string text = client.DownloadString(uri);
            Console.WriteLine(text);
        }
    }

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

暂无
暂无

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

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