HttpWebRequest 编码 - UTF-8

HttpWebRequest Encoding - UTF-8

我正在尝试从网页中获取一些数据,但我遇到了字符问题。网页是 utf-8 格式和多语言,在这种情况下,我可以毫无问题地获取基于英语的 senteces/datas 但对于意大利语、西班牙语和土耳其语数据,我得到了错误的字符。

当我检查保存的 html 文件时,对于文本编码,它说:windows-1254

正如您在我的方法中看到的那样,我试图通过在 streamreader 中使用来解决问题;

    Encoding.GetEncoding("utf-8")
    Encoding.Default
    Encoding.UTF8

HTTP 网络请求:

string postdata = "username" + usern + "&pass=" + pass";
byte[] bytes = new UTF8Encoding().GetBytes(postdata);
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.*******.com/login.php");
request.Method = "POST";
request.KeepAlive = true;
request.CookieContainer = cont;
request.AutomaticDecompression = DecompressionMethods.Deflate;
request.CookieContainer.Add(cok);
request.ContentType = "text/html; charset=utf-8";                  
request.UserAgent = "Mozilla/2.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/9.0";
request.ContentLength = bytes.Length;
request.GetRequestStream().Write(bytes, 0, bytes.Length);

HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();          
StreamReader _str2 = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
 string html = _str2.ReadToEnd();
File.WriteAllText("login_response.html", html);

我相信你的错误不在抓取上,而是在新文件的写入上,所以不要使用 File.WriteAllText,你也许应该看看:

How to write out a text file in C# with a code page other than utf-8?

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

(该页面的示例)。

--- 编辑:

你显然可以在 File.WriteAllText 上做同样的事情:https://msdn.microsoft.com/en-us/library/ms143376(v=vs.110).aspx