如何获取url的内容类型?

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

我想知道如何检测这样的url的内容类型?

它应该是这样的

  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

有关更详细的回复,请提供更详细的问题。

 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类型。 只需在响应标头中查找内容类型即可。

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

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