c#写文件,字符串全是乱码。
public static void WriteFile()
{
string strPath = System.AppDomain.CurrentDomain.BaseDirectory;
strPath += "b.html";
string url = "http://www.wolongyin.com/loginGame.jsp?sid=1002";
string sException = null;
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Accept = "*/*";
webRequest.Method = "GET";
webRequest.Headers.Add("Accept-Language", "zh-CN");
webRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("TGClient", "yes");
webRequest.Host = "www.wolongyin.com";
webRequest.KeepAlive = true;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream streamReceive = response.GetResponseStream();
MessageBox.Show(((int)response.StatusCode).ToString());
MessageBox.Show((response.CharacterSet).ToString());
StreamReader streamReader = new StreamReader(streamReceive, Encoding.GetEncoding(response.CharacterSet));
StreamWriter sw = new StreamWriter(strPath, false, Encoding.GetEncoding(response.CharacterSet));
sw.Write(streamReader.ReadToEnd());
sw.Flush();
sw.Close();
streamReader.Close();
}
catch (WebException e)
{
sException = e.Message.ToString();
throw e;
}
catch (Exception e)
{
sException = e.ToString();
throw e;
}
}
写入全是乱码,不是中文乱码。求大神给个正确的代码。 C# 乱码 String
[解决办法]
你这是写用GET方式传数吧,本人也是新手,你没有写编码格式 Web Request.ContentType = "text/html;charset=UTF-8";
[解决办法]
string strPath = System.AppDomain.CurrentDomain.BaseDirectory;
strPath += "b.html";
string url = "http://www.wolongyin.com/loginGame.jsp?sid=1002";
string sException = null;
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Accept = "*/*";
webRequest.Method = "GET";
webRequest.Headers.Add("Accept-Language", "zh-CN");
webRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("TGClient", "yes");
webRequest.Host = "www.wolongyin.com";
webRequest.KeepAlive = true;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream streamReceive = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamReceive, Encoding.GetEncoding(response.CharacterSet));
string result = streamReader.ReadToEnd();
File.WriteAllText(strPath, result, Encoding.GetEncoding(response.CharacterSet));
}
catch (WebException e)
{
sException = e.Message.ToString();
throw e;
}
catch (Exception e)
{
sException = e.ToString();
throw e;
}
[解决办法]
1.不要设置Accept-Encoding的Header
webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
2.设置Accept-Encoding的Header,同时设置对应的自动解压缩的模式
webRequest.Headers["Accept-Encoding"] = "gzip,deflate";
webRequest.AutomaticDecompression = DecompressionMethods.GZip;
[解决办法]
去掉webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");即可
[解决办法]
+1