【问题标题】:HttpWebRequest Encoding - UTF-8HttpWebRequest 编码 - UTF-8
【发布时间】:2015-11-15 06:46:38
【问题描述】:

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

当我检查保存的 html 文件时,文本编码显示:windows-1254

正如您在我的方法中看到的,我尝试通过在流阅读器中使用来解决问题;

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

Httpweb请求:

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);

【问题讨论】:

    标签: c# utf-8 httpwebrequest


    【解决方案1】:

    我相信你的错误不是在获取,而是在新文件的写入,所以不要使用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

    【讨论】:

    • 是的,你完全正确。我过于关注请求和响应部分。再次感谢您。
    猜你喜欢
    • 2017-01-24
    • 2011-10-30
    • 2012-11-07
    • 2015-03-04
    • 2016-07-05
    • 1970-01-01
    • 2011-04-27
    • 2012-09-22
    • 2019-07-17
    相关资源
    最近更新 更多