是否有可能以正确的编码从web响应中获得数据?
本文关键字:响应 数据 web 有可能 编码 是否 | 更新日期: 2023-09-27 18:10:22
using (WebResponse response = webRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string tmpStreamData = string.Empty;
while (!reader.EndOfStream)
{
while (reader.Peek() > -1)
{
tmpStreamData += (char)reader.Read();
}
}
MessageBox.Show(tmpStreamData);
}
}
有时我得到"tmpStreamData"符号。是否有可能避免这种情况并以可读格式获取数据?
// Get HTTP response. If this is not an HTTP response, you need to know the encoding yourself.
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
// If not an HTTP response, then response.CharacterSet must be replaced by a predefined encoding, e.g. UTF-8.
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
{
// Read whole stream to string.
string tmpStreamData = reader.ReadToEnd();
MessageBox.Show(tmpStreamData);
}
}