HttpWebResponse的编码问题
本文关键字:问题 编码 HttpWebResponse | 更新日期: 2023-09-27 18:16:30
我有从http web响应收到的字符编码问题,我收到?
而不是é
。
我将编码设置为根据网页的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();
你能告诉我有什么问题吗?
在提出请求之前尝试添加以下内容:
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();
}