我从http网络回复收到的字符编码有问题,我收到?
而不是é
。
我将编码设置为Content-Type
的网页的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();
你能告诉我它有什么问题吗?
答案 0 :(得分:2)
在提出请求之前,请尝试添加以下内容:
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1");
顺便说一句,如果您想尝试我提出的解决方案,您应该使用ISO-8859-1(而不是UTF8)保存您的StreamReader。祝你好运!
答案 1 :(得分:1)
您是否尝试过以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();
}