![](/img/trans.png)
[英]How to add the Content-Type header to a .Net GET web request?
[英]How to get content type of a web address?
它應該是這樣的
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。
有兩種方法可以確定內容類型
第一個是微軟在過去的某種程度上推廣的,並且不再是一個好的做法。
如果客戶端具有僅接受某種內容類型的顯示約束,則它將向服務器請求標題
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.