HttpWebRequest 读取网站返回为中文成乱码请指导员

骷髅会-北极熊 2011-12-12 05:28:48
public string GetHtml(string url, string postData, bool isPost, CookieContainer cookieContainer)
{
if (string.IsNullOrEmpty(postData))
{
return GetHtml(url, cookieContainer);
}

Thread.Sleep(delay);
currentTry++;
try
{
byte[] byteRequest = Encoding.Default.GetBytes(postData);

HttpWebRequest httpWebRequest;
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.ContentType = contentType;
httpWebRequest.Referer = url;
httpWebRequest.Accept = accept;
httpWebRequest.UserAgent = userAgent;
httpWebRequest.Method = isPost ? "POST" : "GET";
httpWebRequest.ContentLength = byteRequest.Length;
encode = Encoding.GetEncoding("GB2312");
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(byteRequest, 0, byteRequest.Length);
stream.Close();

HttpWebResponse httpWebResponse;
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, encoding);
string html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();

currentTry = 0;
return html;
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ") + e.Message);
Console.ForegroundColor = ConsoleColor.White;

if (currentTry <= maxTry)
{
GetHtml(url, postData, isPost, cookieContainer);
}

currentTry = 0;
return string.Empty;
}
}

public static string Login(string loginEmail, string loginPassword)
{
string loginUrl = "http://www.222idc.com/user/userlogin.asp";
string postData = string.Format("username={0}&password={1}", loginEmail, loginPassword);
string result = httpHelper.GetHtml(loginUrl, postData, true, cookieContainer);
return result;
}


HttpWebRequest 读取网站返回为中文成乱码请指导员 上以是我使用的代码,还是一个登录加cookieS记录的.

Login为登录事件,可是返回result里的中文全是乱码了.请大虾修改指导员.

...全文
219 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
you97 2011-12-14
  • 打赏
  • 举报
回复
最近也在研究这个东西,想用WEB的去保存别的网站的登录操作怎么做?
  • 打赏
  • 举报
回复
问题解决,非常感谢楼上二位,是我的自己粗心了.问题出在encoding这个变量上.我设置错了.
dalmeeme 2011-12-12
  • 打赏
  • 举报
回复
把StreamReader streamReader = new StreamReader(responseStream, encoding);这句的编码换成utf-8试试,如不行,就是如1楼所说的那样。
机器人 2011-12-12
  • 打赏
  • 举报
回复
用Fiddler抓包看看,有可能返回的是 Gzip 压缩流。

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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