[英]encoding problems with HttpWebResponse
我收到來自http網絡響應的字符編碼問題,我收到了?
而是é
。
我根據text/javascript; charset=ISO-8859
的網頁的Content-Type
設置編碼text/javascript; charset=ISO-8859
text/javascript; charset=ISO-8859
;
我的代碼是:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(..);
request.Method = "GET";
request.AllowAutoRedirect = false;
request.Referer = "Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1";
request.Headers.Add("DNT", "1");
request.Accept = "text/html,application/xhtml+xml,application/xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("iso-8859-1"));
char[] buf = new char[256];
int count;
StringBuilder buffer = new StringBuilder();
while ((count = sr.Read(buf, 0, 256)) > 0)
{
buffer.Append(buf, 0, count);
}
string responseStr = buffer.ToString();
Console.WriteLine(responseStr);
response.Close();
stream.Close();
sr.Close();
你能告訴我它有什么問題嗎?
在提出請求之前,請嘗試添加以下內容:
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1");
順便說一句,如果你想嘗試我提出的解決方案,你應該保留你的StreamReader與ISO-8859-1(而不是UTF8)。 祝好運!
您是否嘗試過以UTF-8設置? 此外,您還發送了一個引薦來源網址,我認為您試圖設置UserAgent。 下面的代碼與您的代碼相同,但不會遍歷字節數組並設置useragent和utf8編碼。
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1";
request.Headers.Add("DNT", "1");
request.Accept = "text/html,application/xhtml+xml,application/xml";
using(var response = (HttpWebResponse)request.GetResponse())
using(var stream = response.GetResponseStream())
using (var sr = new StreamReader(stream, Encoding.UTF8))
{
string responseStr = sr.ReadToEnd();
Console.WriteLine(responseStr);
response.Close();
if (stream != null)
stream.Close();
sr.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.