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

9
我想获取网址的类型。例如,这个是一个Html页面,其页面类型为text/html,但这个的类型是text/xml这个页面的类型似乎是image/png,但实际上是text/html我想知道如何检测像这个这样的网址的内容类型?

一个URL在header中是否有内容类型。 - paparazzo
5个回答

14

应该是这样的

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

我也在这里使用了你的代码[https://dev59.com/3WfWa4cB1Zd3GeqPgV5O],谢谢。 - ahmadali shafiee
6
为了提高速度,也可以添加request.Method = "HEAD"; - IS4
如果 (response != null) contentType = response.ContentType; 可以简写为 contentType = response?.ContentType; (详细信息 - mekb

1

您可以通过响应的 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

1
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类型,而无需下载页面。只需在响应头中查找内容类型即可。


1
很可能 MyClient 是一个支持 HEAD 方法的 WebClient 子类? - Marc Gravell
是的,你说得对。这段代码是从我之前用于检查二进制HTTP响应的另一个示例中复制过来的。 - EdFred
4
如果您链接到那个样例,对读者可能更有用。 - Marc Gravell
带有方法支持的WebClient - Anand Sainath

1

了解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

不要使用自己的标题来指定字符编码。


OP问如何在C#中获取该信息,而不是询问头文件是什么。 - dotancohen

1

HTTP响应头:content-type

如果需要更详细的响应,请提供更详细的问题。


1
OP问如何在C#中获取该信息,而不是询问头文件是什么。 - dotancohen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接