[英]HttpWebResponse encoding
嘗試從google.com獲取html時,編碼出現問題。 請給我一個建議,以解決此問題。 非常感謝。
public string Html
{
get
{
try
{
var request = WebRequest.Create(Url) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1,gzip(gfe)";
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
string Charset = response.CharacterSet;
Encoding encoding = Encoding.GetEncoding(Charset);
var sr = new StreamReader(response.GetResponseStream(), encoding);
return sr.ReadToEnd();
}
}
return string.Format("Could not create object HttpWebRequest for '{0}'", Url);
}
catch (Exception e)
{
return e.Message;
}
}
}
這也是一張圖片:
您面臨的問題是因為某種原因Google不在標頭中發送任何編碼信息。 如果您使用下面的鏈接檢查標題(特別是Content-Type標題),然后將第一個標題(來自圖像)與第二個標題進行比較,您會發現第一個標題缺少一些重要信息。
http://web-sniffer.net/?url=http://www.google.com.ua/intl/ils/ads/
http://web-sniffer.net/?url=http://www.google.de/
在這里您需要做的是首先解析返回的HTML,並尋找一個<meta>
元素,該元素指定編碼,然后使用該新信息重新編碼獲取的流。 取決於您之后對HTML的處理方式,您可能希望將http://htmlagilitypack.codeplex.com/作為使用HTML的出色庫,或者只是編寫一個正則表達式以提取編碼(盡管我真的建議您而是第一種選擇)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.