【问题标题】:How to get content type of a web address?如何获取网址的内容类型?
【发布时间】:2012-08-10 07:48:53
【问题描述】:

我想获取网址的类型。例如this是一个Html页面,它的页面类型是text/html,但是this 的类型是text/xmlthis 页面的类型似乎是 image/png 但它是 text/html

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

【问题讨论】:

  • 不应该是这样。 URL 是否在标头中有内容类型。

标签: c# .net c#-4.0 content-type


【解决方案1】:

HTTP 响应头:content-type

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

【讨论】:

  • OP 询问如何在 C# 中获取该信息,而不是标题是什么。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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 类型。只需在响应标头中查找内容类型即可。

    【讨论】:

    • 大概MyClientWebClient 的子类,支持HEAD
    • 是的,你是对的。这是从我用于检查二进制 http 响应的另一个示例中复制的。
    • 如果您链接到其他示例,它可能对读者更有用:)
    • WebClient 支持方法 -
    【解决方案4】:

    应该是这样的

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

    【讨论】:

    • 我也使用了你的代码here 谢谢。
    • request.Method = "HEAD"; 也可以添加以提高速度。
    • if (response != null) contentType = response.ContentType; 可以短接为contentType = response?.ContentType; (info here)
    【解决方案5】:

    阅读 HTTP 标头。

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

    内容类型:应用程序/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
    

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

    【讨论】:

    • OP 询问如何在 C# 中获取该信息,而不是标题是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2012-09-13
    • 2020-06-16
    相关资源
    最近更新 更多