我用HttpWebResponse取的网页内容中文为什么是乱码,怎么解决?

regex2012 2011-03-09 11:23:47
如题!
...全文
306 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
regex2012 2011-03-09
  • 打赏
  • 举报
回复
wxr0323兄,GetHtml(string url, Encoding encoding)中的encoding如何自动识别呢?
regex2012 2011-03-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 wxr0323 的回复:]
统一编码 UTF-8 或者 GB2312


C# code

static string GetHtml(string url, Encoding encoding)
{
byte[] buf = new WebClient().DownloadData(url);
if (encoding != null) return encoding.GetString(b……
[/Quote]

目前有门,测试中。。。
regex2012 2011-03-09
  • 打赏
  • 举报
回复
不行呀,还是有乱码,有一少部分变成??了
KeepMoving 2011-03-09
  • 打赏
  • 举报
回复
看看你的编码方式,改一下试试!
子夜__ 2011-03-09
  • 打赏
  • 举报
回复
统一编码 UTF-8 或者 GB2312


static string GetHtml(string url, Encoding encoding)
{
byte[] buf = new WebClient().DownloadData(url);
if (encoding != null) return encoding.GetString(buf);
string html = Encoding.UTF8.GetString(buf);
encoding = GetEncoding(html);
if (encoding == null || encoding == Encoding.UTF8) return html;
return encoding.GetString(buf);
}


static Encoding GetEncoding(string html)
{
string pattern = @"(?i)\bcharset=(?<charset>[-a-zA-Z_0-9]+)";
string charset = Regex.Match(html, pattern).Groups["charset"].Value;
try { return Encoding.GetEncoding(charset); }
catch (ArgumentException) { return null; }
}
小童 2011-03-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 fangxinggood 的回复:]
C# code

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebRespo……
[/Quote]+
beckfun 2011-03-09
  • 打赏
  • 举报
回复
读取内容的编码
马老虎 2011-03-09
  • 打赏
  • 举报
回复
试一试GB2312编码。
根据你抓取页面的内容找到相应的编码
  • 打赏
  • 举报
回复

百度一下
机器人 2011-03-09
  • 打赏
  • 举报
回复

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
string strResponse = readStream.ReadToEnd();

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧