应该是这样的
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;
}
request.Method = "HEAD";
。 - IS4您可以通过响应的 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
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类型,而无需下载页面。只需在响应头中查找内容类型即可。
MyClient
是一个支持 HEAD
方法的 WebClient
子类? - Marc Gravell了解HTTP头。
HTTP头将告诉您内容类型。例如:
content-type: application/xml。
有两种方法可以确定内容类型
第一种方法在旧时代曾经被微软推广,但现在已不再是一个好的实践。
如果客户端有显示限制,只接受某些内容类型,则会使用类似以下的头请求服务器
accept: application/json
accept: text/html
accept: application/xml
如果服务器可以提供其中之一并选择XML,则会返回带有标头的内容。
content-type: application/xml.
然而,一些服务包括更多的信息,例如
content-type: application/xml; charset=utf-8
不要使用自己的标题来指定字符编码。
HTTP响应头:content-type
如果需要更详细的响应,请提供更详细的问题。